Pagini recente » Cod sursa (job #406548) | Cod sursa (job #2255014) | Cod sursa (job #2373552) | Cod sursa (job #284583) | Cod sursa (job #2964983)
#include <fstream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int n,m,d[50001],cnt[50001],a,b,c;
bool inq[500001];
vector<pair<int,int>> g[50001];
bool spfa(int nod)
{
for(int i=1;i<=n;i++)
d[i]=2e9;
queue<int> q;
q.push(nod);
d[nod]=0;
inq[nod]=1;
while(!q.empty())
{
int a=q.front();
q.pop();
inq[a]=0;
for(auto &i:g[a])
{
if(d[i.first]>d[a]+i.second)
{
d[i.first]=d[a]+i.second;
if(!inq[i.first])
{
inq[i.first]=1;
q.push(i.first);
cnt[i.first]++;
if(cnt[i.first]>=n)
{
cout<<"Ciclu negativ!";
return 0;
}
}
}
}
}
return 1;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m;
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
g[a].push_back({b,c});
}
if(!spfa(1))
return 0;
for(int i=2;i<=n;i++)
cout<<d[i]<<' ';
return 0;
}