Pagini recente » Cod sursa (job #214917) | Cod sursa (job #1848876) | Cod sursa (job #2052565) | Arhiva de probleme | Cod sursa (job #1714779)
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 50005
#define INF 0x3F3F3F3F
using namespace std;
int N, M, cost[NMAX], used[NMAX];
bool negativeCycle;
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] = 1;
cost[root] = 0;
while (!q.empty()) {
node = q.front();
q.pop();
used[node]++;
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;
q.push(it -> second);
used[it -> second]++;
if (used[it -> second] > N) {
negativeCycle = true;
return;
}
}
}
}
}
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();
}