Pagini recente » Cod sursa (job #2655824) | Cod sursa (job #333524) | Cod sursa (job #2899956) | Cod sursa (job #508638) | Cod sursa (job #2073939)
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 50000;
const int INF = 2000000000;
int n;
vector <pair <int, int> > g[NMAX+5];
bool in_queue[NMAX+5];
int vis[NMAX+5];
int dist[NMAX+5];
void Bellman_ford(int nod)
{
queue <int> q;
dist[nod] = 0;
q.push(nod);
in_queue[nod] = true;
while(!q.empty())
{
int top = q.front();
q.pop();
in_queue[top] = false;
for(int i=0; i<g[top].size(); i++)
{
pair <int, int> New = g[top][i];
if(dist[nod] + New.second < dist[New.first])
{
dist[New.first] = dist[nod] + New.second;
if(!in_queue[New.first])
{
if(vis[New.first] > n)
{
printf("Ciclu negativ!\n");
return;
}
in_queue[New.first] = true;
q.push(New.first);
vis[New.first]++;
}
}
}
}
for(int i=2; i<=n; i++)
printf("%d ", dist[i]);
printf("\n");
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int m;
scanf("%d%d", &n, &m);
for(int i=0; i<m; i++)
{
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
g[x].push_back(pair <int, int> (y, c));
}
for(int i=1; i<=n; i++)
dist[i] = INF;
Bellman_ford(1);
return 0;
}