Pagini recente » Cod sursa (job #2357936) | Cod sursa (job #571048) | Cod sursa (job #1770428) | Cod sursa (job #1571671) | Cod sursa (job #1839242)
#include <bits/stdc++.h>
using namespace std;
#define SIZE(x) ((int) (x).size())
#define ALL(x) (x).begin(), (x).end()
typedef long long int64; typedef unsigned long long uint64;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
const int NMAX = 50005;
vector<pair<int, int>> g[NMAX];
int dist[NMAX];
int N, M;
bool bellmanFordFast(int source) {
queue<int> q;
bitset<NMAX> inq(false);
vector<int> countq(NMAX, 0);
bool cycle = false;
dist[source] = 0; q.push(source); inq[source].flip(); countq[source]++;
while (!q.empty() && !cycle) {
int u = q.front(); q.pop();
inq[u] = false;
for (pair<int, int>& e : g[u]) {
int v = e.second, w = e.first;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
if (!inq[v]) {
if (countq[v] > N) { cycle = true; break; }
else { q.push(v), countq[v]++, inq[v] = true; }
}
}
}
}
return !cycle;
}
int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++) {
int x, y, w; scanf("%d %d %d", &x, &y, &w);
g[x].push_back({w, y});
}
memset(dist, INF, sizeof(dist));
int ret = bellmanFordFast(1);
if (!ret) {
printf("Ciclu negativ!\n");
return 0;
}
int num = 0;
for (int i = 2; i <= N; i++) {
if (num++) printf(" ");
printf("%d", dist[i]);
}
printf("\n");
return 0;
}