Pagini recente » Cod sursa (job #2931481) | Cod sursa (job #2599200) | Cod sursa (job #3256801) | Cod sursa (job #1914369) | Cod sursa (job #1445603)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <cstdlib>
using namespace std;
const int nmx = 50005, inf = 0x3f3f3f3f;
int n, dist[nmx], nr_vizite[nmx];
vector <pair <int,int> > g[nmx];
inline void citire() {
int m, nod1, nod2, cost;
scanf("%d %d", &n, &m);
for(; m; --m) {
scanf("%d %d %d", &nod1, &nod2, &cost);
g[nod1].push_back(make_pair(nod2,cost)); /// pereche ( nod , cost )
}
}
inline void bellmanford() {
memset(dist, inf, sizeof(dist));
dist[1] = 0;
queue <int> q;
q.push(1);
int nod_curent, nr_vecini;
while(not q.empty()) {
nod_curent = q.front();
q.pop();
nr_vecini = g[nod_curent].size();
for(int i = 0; i < nr_vecini; ++i)
if(dist[g[nod_curent][i].first] > dist[nod_curent] + g[nod_curent][i].second) {
dist[g[nod_curent][i].first] = dist[nod_curent] + g[nod_curent][i].second;
q.push(g[nod_curent][i].first);
if(++ nr_vizite[g[nod_curent][i].first] > n){
printf("Ciclu negativ!\n");
exit(0);
}
}
}
}
inline void afish(){
for(int i = 2; i <= n; ++i)
printf("%d ", dist[i]);
}
int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
citire();
bellmanford();
afish();
return 0;
}