Pagini recente » Cod sursa (job #3309784) | Cod sursa (job #3334494) | Cod sursa (job #595215) | Cod sursa (job #1135503) | Cod sursa (job #3324183)
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <fstream>
#include <bitset>
#include <queue>
#include <map>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<pair<int, int>> graph[50001];
bitset<50001> isInQueue;
long long minDist[50001];
int noUpdates[50001];
int n, m;
bool negativeCycleFound;
void bfs(int startNode) {
queue<int> q;
q.push(startNode);
isInQueue[startNode] = 1;
minDist[startNode] = 0;
while (!q.empty() && negativeCycleFound == 0) {
int currentNode = q.front();
q.pop();
isInQueue[currentNode] = 0;
if (noUpdates[currentNode] > n - 1) {
negativeCycleFound = 1;
}
for (vector<pair<int, int>>::iterator it = graph[currentNode].begin(); it != graph[currentNode].end(); ++it) {
if (minDist[currentNode] + it->second < minDist[it->first]) {
++noUpdates[it->first];
minDist[it->first] = minDist[currentNode] + it->second;
if (isInQueue[it->first] == 0) {
q.push(it->first);
isInQueue[it->first] = 1;
}
}
}
}
}
int main() {
fin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x].push_back({y, c});
}
for (int i = 1; i <= n; ++i) {
minDist[i] = 1e18;
}
bfs(1);
if (negativeCycleFound == 0) {
for (int i = 2; i <= n; ++i) {
fout << minDist[i] << ' ';
}
} else {
fout << "Ciclu negativ!";
}
return 0;
}