Pagini recente » Cod sursa (job #1452711) | Cod sursa (job #2622311) | Cod sursa (job #2590240) | Cod sursa (job #197083) | Cod sursa (job #1823227)
#include <cstdio>
#include <queue>
#include <algorithm>
#define inf 1000000000
using namespace std;
vector< pair<int, int> > g[50000];
int n, m;
queue<int> q;
bool viz[50000] = {0};
int nr[50000] = {0};
int dist[50000];
int main()
{
int i, j, a, b, c;
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d%d", &n, &m);
for(i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &c);
a--; b--;
g[a].push_back(make_pair(b, c));
}
for(i = 1; i < n; i++)
dist[i] = inf;
q.push(0);
nr[0] = 1;
while(!q.empty())
{
a = q.front();
q.pop();
viz[a] = 0;
for(i = 0; i < g[a].size(); i++)
{
if(dist[g[a][i].first] > dist[a] + g[a][i].second)
{
dist[g[a][i].first] = dist[a] + g[a][i].second;
if(viz[g[a][i].first] == 0)
{
viz[g[a][i].first] = 1;
q.push(g[a][i].first);
nr[g[a][i].first]++;
if(nr[g[a][i].first] >= n)
{
printf("Ciclu negativ!");
return 0;
}
}
}
}
}
for(i = 1; i < n; i++)
{
printf("%d ", dist[i]);
}
return 0;
}