Pagini recente » Cod sursa (job #2619031) | Cod sursa (job #2755371) | Cod sursa (job #1203168) | Cod sursa (job #383106) | Cod sursa (job #2526750)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector< pair< int, int> > g[50005];
int dist[50005];
int n, m;
bool ciclu;
int cnt[500005];
queue<int> q;
void citire() {
fin >> n >> m;
int a, b, c;
for(int i = 1; i <= m; i++) {
fin >> a >> b >> c;
g[a].push_back({b, c});
}
}
void solve() {
q.push(1);
for(int i = 1; i <= n; i++)
dist[i] = 100000000;
dist[1] = 0;
while(!q.empty() && !ciclu) {
int curr = q.front();
q.pop();
cnt[curr]++;
if(cnt[curr] > n) {
ciclu = true;
return;
}
for(int i = 0; i < g[curr].size(); i++) {
int next = g[curr][i].first, c = g[curr][i].second;
if(dist[curr]+c < dist[next]) {
dist[next] = dist[curr]+c;
q.push(next);
}
}
}
}
void afis() {
if(ciclu)
fout << "Ciclu negativ!";
else
for(int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
int main() {
citire();
solve();
afis();
}