Pagini recente » Cod sursa (job #479331) | Cod sursa (job #1861270) | Cod sursa (job #2901531) | Cod sursa (job #2546653) | Cod sursa (job #1916070)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
#define maxn 50005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m;
int dist[maxn];
int inQueue[maxn], countQueue[maxn];
bool negativeCycle = false;
vector < pair <int, int> > v[maxn];
queue <int> Q;
void BellmanFord(){
for(int i = 2; i <= n; ++i) dist[i] = INF;
Q.push(1);
while(!Q.empty() && !negativeCycle){
int u = Q.front();
Q.pop();
inQueue[u] = 0;
for(int i = 0; i < v[u].size(); ++i){
int nod = v[u][i].first;
int distance = v[u][i].second;
//if(dist[u] < INF){
if(dist[nod] > dist[u] + distance){
dist[nod] = dist[u] + distance;
if(!inQueue[nod]){
if(countQueue[nod] > n){
negativeCycle = true;
}
else{
inQueue[nod] = 1;
countQueue[nod]++;
Q.push(nod);
}
}
}
//}
}
}
}
int main (){
f >> n >> m;
for(int i = 1; i <= m; ++i){
int x, y, d;
f >> x >> y >> d;
v[x].push_back(make_pair(y, d));
}
BellmanFord();
if(negativeCycle) g << "Ciclu negativ!\n";
else for(int i = 2; i <= n; ++i) g << dist[i] << ' ';
}