Pagini recente » Cod sursa (job #867392) | Cod sursa (job #3129245) | Cod sursa (job #3210729) | Cod sursa (job #3222467) | Cod sursa (job #3269621)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int N = 50005;
const int M = 250005;
const int INF = 1 << 30;
struct muchie {
int dest, cost;
};
vector<muchie> graf[N];
int cost[N];
bool inqueue[N];
int nrimprove[N];
int main()
{
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int x, y, c;
cin >> x >> y >> c;
graf[x].push_back({y, c});
}
cost[1] = 0;
for(int i = 2; i <= n; i++) {
cost[i] = INF;
}
queue<int> q;
q.push(1);
inqueue[1] = true;
nrimprove[1] = 1;
while(!q.empty()) {
int now = q.front();
q.pop();
inqueue[now] = false;
for(muchie mu : graf[now]) {
if(cost[now] + mu.cost < cost[mu.dest]) {
cost[mu.dest] = cost[now] + mu.cost;
nrimprove[mu.dest]++;
if(nrimprove[mu.dest] > n) {
cout << "Ciclu negativ!";
return 0;
}
if(!inqueue[mu.dest]) {
q.push(mu.dest);
inqueue[mu.dest] = true;
}
}
}
}
for(int i = 2; i <= n; i++) {
cout << cost[i] << ' ';
}
return 0;
}