Pagini recente » Diferente pentru preoji/clasament/11-12 intre reviziile 21 si 19 | Cod sursa (job #2814943) | Cod sursa (job #353931) | Statistici Apopei Roxana (roxanaapopei) | Cod sursa (job #2085609)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 50000;
const int INF = (1LL << 31) - 1;
vector<pair<int, int> >G[MAX_N + 5];
int dist[MAX_N + 5];
int nrv[MAX_N + 5];
int inc[MAX_N + 5];
int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i) {
int u, v, c;
scanf("%d%d%d", &u, &v, &c);
G[u].push_back(make_pair(v, c));
}
for (int i = 1; i <= n; ++i) {
dist[i] = INF;
nrv[i] = 0;
inc[i] = 0;
}
inc[1] = 1;
nrv[1] = 1;
dist[1] = 0;
queue<int>q;
q.push(1);
while (!q.empty() && nrv[q.front()] < n) {
int node = q.front();
q.pop();
inc[node] = 0;
for (auto it:G[node]) {
if (dist[node] + it.second < dist[it.first]) {
dist[it.first] = dist[node] + it.second;
if (inc[it.first] == 0) {
inc[it.first] = 1;
q.push(it.first);
nrv[it.first]++;
}
}
}
}
if (!q.empty()) {
printf("Ciclu negativ!");
} else {
for (int i = 2; i <= n; ++i)
printf("%d ", dist[i]);
}
return 0;
}