Pagini recente » Cod sursa (job #23896) | Cod sursa (job #2404675) | Cod sursa (job #1328328) | Cod sursa (job #1425866) | Cod sursa (job #2570682)
#include <bits/stdc++.h>
#define lsb(x) (x & (-x))
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
const int INF = 1e9;
int main() {
#ifdef HOME
ifstream cin("A.in");
ofstream cout("A.out");
#endif
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int i, n, m;
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n >> m;
vector <vector <pair <int, int>>> g(n + 1);
for(i = 1; i <= m; i++) {
int x, y, z; cin >> x >> y >> z;
g[x].push_back({y, z});
}
vector <int> dst(n + 1, INF), num(n + 1);
vector <bool> inq(n + 1);
queue <int> Q;
Q.push(1), dst[1] = 0;
inq[1] = 1;
while(Q.size()) {
int nod = Q.front();
Q.pop();
if(num[nod] == n) {
cout << "Ciclu negativ!";
return 0;
}
num[nod]++, inq[nod] = 0;
for(auto it : g[nod]) {
if(dst[it.first] > dst[nod] + it.second) {
dst[it.first] = dst[nod] + it.second;
if(inq[it.first] == 0) {
Q.push(it.first);
inq[it.first] = 1;
}
}
}
}
for(i = 2; i <= n; i++) {
cout << dst[i] << " ";
}
return 0;
}