Pagini recente » Cod sursa (job #1217633) | Cod sursa (job #777983) | Cod sursa (job #1405288) | Cod sursa (job #613769) | Cod sursa (job #2636828)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int inf = 1000000000;
int n, m;
vector<pair<int, int> > g[50005];
int dist[50005], aparitii[50005];
queue<int> q;
void citire() {
fin >> n >> m;
while(m--) {
int x, y, c;
fin >> x >> y >> c;
g[x].push_back({y, c});
}
}
void solve() {
for(int i = 1; i<= n; i++)
dist[i] = inf;
dist[1] = 0;
q.push(1);
while(!q.empty()) {
int x = q.front();
q.pop();
aparitii[x]++;
if(aparitii[x] > n) {
fout << "Ciclu negativ!";
return;
}
for(auto next: g[x])
if(dist[next.first] > dist[x]+next.second) {
dist[next.first] = dist[x]+next.second;
q.push(next.first);
}
}
for(int i = 2; i<= n; i++)
fout << dist[i] << ' ';
}
int main() {
citire();
solve();
}