Pagini recente » Cod sursa (job #1476475) | Cod sursa (job #2094456) | Cod sursa (job #3281509) | Cod sursa (job #921848) | Cod sursa (job #1714776)
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 50005
#define INF 0x3F3F3F3F
using namespace std;
int N, M, cost[NMAX], noUsed;
bool negativeCycle, used[NMAX];
vector <pair <int, int> > graph[NMAX];
void read() {
int x, y, c;
scanf("%d %d", &N, &M);
for (int i = 1; i <= M; ++i) {
scanf("%d %d %d", &x, &y, &c);
graph[x].push_back(make_pair(c, y));
}
memset(cost, INF, sizeof(cost));
}
void bellmanFord(int root) {
queue <int> q;
vector <pair <int, int> > :: iterator it;
int node;
q.push(root);
used[root] = true;
noUsed++;
cost[root] = 0;
while (!q.empty()) {
if (noUsed > N) {
negativeCycle = true;
return;
}
node = q.front();
q.pop();
used[node] = false;
noUsed--;
for (it = graph[node].begin(); it != graph[node].end(); ++it) {
if (cost[it -> second] > cost[node] + it -> first) {
cost[it -> second] = cost[node] + it -> first;
if (!used[it -> second]) {
q.push(it -> second);
used[it -> second] = true;
noUsed++;
}
}
}
}
}
void print() {
if (negativeCycle) {
printf("Ciclu negativ!");
}
else {
for (int i = 2; i <= N; ++i) {
printf("%d ", cost[i]);
}
}
}
int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
read();
bellmanFord(1);
print();
}