Pagini recente » Cod sursa (job #2522536) | Cod sursa (job #2332073) | Cod sursa (job #2977990) | Cod sursa (job #1504236) | Cod sursa (job #2369839)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
int viz[50001], d[50001];
const int INF=1e9;
vector<pair<int, int>>G[50001];
queue<int>coada;
int main()
{
fin>>n>>m;
for(int i=1; i<=m; ++i)
{
int x, y, c;
fin>>x>>y>>c;
G[x].push_back(make_pair(y, c));
}
for(int i=1; i<=n; ++i) d[i]=INF;
d[1]=0;
coada.push(1);
while(!coada.empty())
{
int nod=coada.front();
coada.pop();
++viz[nod];
if(viz[nod]>n)
{
fout<<"Ciclu negativ!\n";
return 0;
}
for(auto it:G[nod])
{
if(d[it.first]>d[nod]+it.second)
{
d[it.first]=d[nod]+it.second;
coada.push(it.first);
}
}
}
for(int i=2; i<=n; ++i) fout<<d[i]<<" ";
return 0;
}