Pagini recente » Cod sursa (job #2024607) | Cod sursa (job #72433) | Cod sursa (job #2343553) | Cod sursa (job #3175879) | Cod sursa (job #3219489)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
#define MAXN 50000
#define MAXM 250000
#define INF 250000000
vector<pair<int, int>> v[MAXN+1];
queue<int> q;
vector<int> dist(MAXN+1, INF);
int f[MAXN+1];
int n, m;
void bellmanford(int poz) {
int x, y, c, check;
check=0;
dist[poz]=0;
q.push(poz);
while(!q.empty() && check==0) {
x=q.front();
q.pop();
for(auto i:v[x]) {
y=i.first;
c=i.second;
if(dist[y]>dist[x]+c) {
q.push(y);
f[y]++;
if(f[y]==n) check=1;
dist[y]=dist[x]+c;
}
}
}
if(check==0) {
int i;
for(i=1; i<=n; i++)
if(i!=poz)
cout<<dist[i]<<" ";
} else
cout<<"Ciclu negativ!";
}
int main() {
cin>>n>>m;
int i, x, y, c;
for(i=0; i<m; i++) {
cin>>x>>y>>c;
v[x].push_back({y, c});
}
bellmanford(1);
}