Pagini recente » Cod sursa (job #1839126) | Cod sursa (job #2093649)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
#define pb push_back
typedef long long ll;
const int NMax = 1e5 + 5;
const int inf = 1e9 + 5;
int N,M;
int nrInQueue[NMax],dist[NMax];
vector< pair<int,int> > v[NMax];
int main() {
in>>N>>M;
for (int i=1;i <= M;++i) {
int x,y,c;
in>>x>>y>>c;
v[x].pb( {y,c} );
}
for (int i=1;i <= N;++i) {
dist[i] = inf;
}
dist[1] = 0;
queue< pair<int,int> > Q;
Q.push({1,0});
bool negativeCycle = false;
while (Q.size()) {
auto p = Q.front(); Q.pop();
int node = p.first, nodeDist = p.second;
if (dist[node] < nodeDist) {
continue;
}
++nrInQueue[node];
if (nrInQueue[node] == N) {
negativeCycle = true;
break;
}
for (auto p : v[node]) {
int nxt = p.first, nxtCost = p.second;
if (dist[nxt] < nodeDist + nxtCost) {
continue;
}
dist[nxt] = nodeDist + nxtCost;
Q.push( {nxt,dist[nxt]} );
}
}
if (negativeCycle) {
out<<"Ciclu negativ!\n";
}
else {
for (int i=2;i <= N;++i) {
out<<dist[i]<<' ';
}
}
in.close();out.close();
return 0;
}