Pagini recente » Cod sursa (job #2804096) | Cod sursa (job #2442604) | Cod sursa (job #698563) | Cod sursa (job #1027141) | Cod sursa (job #2561134)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 50005;
const int INF = 1e9;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector < pair <int, int> > g[NMAX];
queue < pair <int, int> > q;
int viz[NMAX], dist[NMAX];
bool bfs(int n)
{
bool neg = 0;
q.emplace(1, 0);
while(!q.empty()) {
pair <int, int> curr = q.front();
q.pop();
viz[curr.first]++;
if(viz[curr.first] == n) {
neg = 1;
break;
}
if(dist[curr.first] >= curr.second) {
dist[curr.first] = curr.second;
for(auto x: g[curr.first]) {
if(dist[x.first] > dist[curr.first] + x.second) {
dist[x.first] = dist[curr.first] + x.second;
q.emplace(x.first, dist[x.first]);
}
}
}
}
return neg;
}
int main() {
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; ++i) {
int x, y, cost;
cin >> x >> y >> cost;
g[x].emplace_back(y, cost);
}
for(int i = 1; i <= n; ++i)
dist[i] = INF;
if(bfs(n)) {
cout << "Ciclu negativ!\n";
} else {
for(int i = 2; i <= n; ++i) {
cout << dist[i] << " ";
}
cout << "\n";
}
return 0;
}