Pagini recente » Cod sursa (job #359487) | Cod sursa (job #760068) | Cod sursa (job #1524141) | Cod sursa (job #1020729) | Cod sursa (job #2238010)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ifstream fout("bellmanford.out");
#define MAXN 50005
#define INF 0x3f3f3f3f
struct Node {
int node;
int cost;
};
vector<Node> graf[MAXN];
int costUntil[MAXN];
int timesVisited[MAXN];
int main() {
int n, m;
fin >> n >> m;
// Citire
for(int i = 1; i <= m; i++) {
int x;
Node crt;
fin >> x >> crt.node >> crt.cost;
graf[x].push_back(crt);
}
for(int i = 1; i<= n; i++)
costUntil[i] = INF;
queue<int> q;
q.push(1);
costUntil[1] = 0;
bool negativeCycle = false;
while(!negativeCycle && !q.empty()) {
int crtNode = q.front(); q.pop();
for(int i = 0 ; i < graf[crtNode].size(); i++) {
Node nextNode = graf[crtNode][i];
if(costUntil[nextNode.node] > costUntil[crtNode] + nextNode.cost) {
timesVisited[nextNode.node]++;
if(timesVisited[nextNode.node] > n) {
negativeCycle = true;
}
costUntil[nextNode.node] = costUntil[crtNode] + nextNode.cost;
q.push(nextNode.node);
}
}
}
if(negativeCycle) {
cout << "Ciclu negativ!";
} else {
for(int i = 2; i <= n; i++) {
cout << costUntil[i] << " ";
}
}
return 0;
}