Pagini recente » Cod sursa (job #2136329) | Cod sursa (job #2066084) | Cod sursa (job #1250119) | Cod sursa (job #2845935) | Cod sursa (job #2575868)
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<vector<pair<int,int>>>G;
int n,m,D[50005],C[50005];
const int INF=0x3f3f3f3f;
bool ciclu;
void BF()
{
for(int i=2;i<=n;++i)
D[i]=INF;
queue<int>Q;
Q.push(1);
while(!Q.empty())
{
int x=Q.front();
++C[x];
if(C[x]==n)
{
ciclu=true;
return;
}
Q.pop();
for(auto p : G[x])
{
int y = p.second;
int w = p.first;
if(D[y]>D[x]+w)
{
D[y]=D[x]+w;
Q.push(y);
}
}
}
}
int main()
{
fin>>n>>m;
G.resize(n+1);
for(int i=1;i<=m;++i)
{
int x,y,w;
fin>>x>>y>>w;
G[x].push_back({w,y});
}
BF();
if(ciclu)
{
fout<<"Ciclu negativ!";
}
else
{
for(int i=2;i<=n;++i)
fout<<D[i]<<" ";
}
return 0;
}