Pagini recente » Cod sursa (job #64704) | Cod sursa (job #3217782) | Cod sursa (job #3210657) | Cod sursa (job #12669) | Cod sursa (job #523281)
Cod sursa(job #523281)
#include <fstream>
#include <iostream>
#include <string.h>
#include <queue>
#include <limits.h>
#include <bitset>
using namespace std;
struct nod {
nod* next;
int vec, val;
};
nod* vecini[50001];
int bestDist[50001];
int used[50001];
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int bellman_ford(nod** vecini,int n) {
for (int i=0; i<n; i++) {
bestDist[i] = INT_MAX/2;
}
bitset<50001> in_queue;
queue<int> q;
q.push(0); in_queue[0] = true; used[0] = 1;
bestDist[0] = 0;
while (!q.empty()) {
int node = q.front();
q.pop(); in_queue[node] = 0;
nod* cur = vecini[node];
while (cur) {
if (bestDist[node] + cur->val < bestDist[cur->vec]) {
bestDist[cur->vec] = bestDist[node] + cur->val;
if (!in_queue[cur->vec]) {
in_queue[cur->vec] = true;
q.push(cur->vec);
used[cur->vec]++;
if (used[cur->vec]>n) return -1; // negative cycle
}
}
cur = cur->next;
}
}
return 0;
}
int main() {
int n, m;
in >> n >> m;
memset(vecini, 0, sizeof(vecini));
memset(used, 0, sizeof(used));
for (int i=0; i<m; i++) {
int x, y, cost;
in >> x >> y >> cost;
x--; y--;
nod* newNode = new nod;
newNode->next = vecini[x];
newNode->vec = y;
newNode->val = cost;
vecini[x] = newNode;
}
if (bellman_ford(vecini, n) == -1) {
out << "Ciclu negativ!" << endl;
return 0;
}
for (int i=1; i<n; i++)
out << bestDist[i] << " ";
out << endl;
return 0;
}