Pagini recente » Cod sursa (job #1866786) | Cod sursa (job #1021377) | Cod sursa (job #318926) | Cod sursa (job #3124870) | Cod sursa (job #1921686)
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector< pair<int, int> > g[50001];
int viz[50001];
int inQueue[50001];
int dist[50001];
int main()
{
int n, m, a, b, c;
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &c);
g[a].push_back(make_pair(b, c));
//g[b].push_back(make_pair(a, c));
}
for(int i = 2; i <= n; i++)
dist[i] = 0x3f3f3f3f;
queue<int> q;
q.push(1);
inQueue[1] = 1;
viz[1] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
inQueue[nod] = 0;
for(int i = 0; i < g[nod].size(); i++)
{
if(dist[g[nod][i].first] > dist[nod] + g[nod][i].second)
{
dist[g[nod][i].first] = dist[nod] + g[nod][i].second;
if(!inQueue[g[nod][i].first])
{
if(viz[g[nod][i].first]++ == n)
{
printf("Ciclu negativ!");
return 0;
}
q.push(g[nod][i].first);
inQueue[g[nod][i].first] = 1;
}
}
}
}
for(int i = 2; i <= n; i++)
printf("%d ", dist[i]);
return 0;
}