Pagini recente » Cod sursa (job #1401879) | Cod sursa (job #1932070) | Cod sursa (job #750215) | Cod sursa (job #2852967) | Cod sursa (job #2558158)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream inf("bellmanford.in");
ofstream outf("bellmanford.out");
const int NMAX = 50001;
struct Muchie {
int to, c;
};
vector<Muchie> ad[NMAX];
queue<int> q;
bool inq[NMAX];
int cnt[NMAX];
int dist[NMAX];
int main() {
int n, m, x, y, c;
inf >> n >> m;
for(int i = 0; i < m; i++) {
inf >> x >> y >> c;
ad[x].push_back({y, c});
}
q.push(1);
inq[1] = true;
cnt[1] = 1;
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
while(!q.empty()) {
x = q.front();
q.pop();
inq[x] = false;
for(Muchie mu : ad[x]) {
if(dist[mu.to] > dist[x] + mu.c) {
dist[mu.to] = dist[x] + mu.c;
if(!inq[mu.to]) {
inq[mu.to] = true;
cnt[mu.to]++;
if(cnt[mu.to] > n) {
outf << "Ciclu negativ!";
return 0;
}
q.push(mu.to);
}
}
}
}
for(int i = 2; i <= n; i++) {
outf << dist[i] << ' ';
}
return 0;
}