Pagini recente » Monitorul de evaluare | Profil NicuAlina | Cod sursa (job #223619) | Monitorul de evaluare | Cod sursa (job #1998488)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int i,n,m,x,y,a,b,c,s,nr,mn,sol[50005];
vector <pair<int,int>> t[50005];
bool viz[50005];
int cnt[50005];
queue <int> coada;
bool e;
void bfs()
{
int i,k;
coada.push(1);
sol[1]=1;
while (!coada.empty())
{
k=coada.front();
if (cnt[k]>n) { e=1; return; }
viz[k]=0;
coada.pop();
for (i=0; i<t[k].size(); i++)
{
if (t[k][i].second+sol[k]<sol[t[k][i].first] || sol[t[k][i].first]==0)
{
sol[t[k][i].first]=t[k][i].second+sol[k];
if (viz[t[k][i].first]==0)
{
coada.push(t[k][i].first);
viz[t[k][i].first]=1;
cnt[t[k][i].first]++;
}
}
}
}
}
int main()
{
fin>>n>>m;
for (i=1; i<=m; i++)
{
fin>>a>>b>>c;
t[a].push_back(make_pair(b,c));
}
bfs();
if (e) fout<<"Ciclu negativ!"; else
{
for (i=2; i<=n; i++)
if (sol[i]==0) fout<<0<<" "; else fout<<sol[i]-1<<" ";
}
}