Pagini recente » Cod sursa (job #2457177) | Cod sursa (job #1499715) | Cod sursa (job #1458393) | Cod sursa (job #1841894) | Cod sursa (job #1453980)
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <stack>
#include <algorithm>
#define nmx 50005
#define inf 0x3f3f3f3f
using namespace std;
int n, m, vizite[nmx], dist[nmx];
vector <pair<int,int> > g[nmx];
queue <int> q;
void bellmanford(){
memset(dist, inf, sizeof(dist));
q.push(1);
dist[1] = 0;
while(not q.empty()){
int nod = q.front();
q.pop();
++ vizite[nod];
if(vizite[nod] > n){
printf("Ciclu negativ!");
exit(0);
}
for(vector<pair<int,int> >::iterator it = g[nod].begin(); it != g[nod].end(); ++it)
if(dist[it->first] > dist[nod] + it->second){
dist[it->first] = dist[nod] + it->second;
q.push(it->first);
}
}
}
int main(){
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d %d", &n, &m);
for(; m; --m){
int nod1, nod2, cost;
scanf("%d %d %d", &nod1, &nod2, &cost);
g[nod1].push_back(make_pair(nod2,cost));
}
bellmanford();
for(int i = 2; i <= n; ++i)
printf("%d ", dist[i]);
return 0;
}