Pagini recente » Cod sursa (job #757428) | Cod sursa (job #2505566) | Cod sursa (job #1037115) | Cod sursa (job #1830447) | Cod sursa (job #2722090)
#include <iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
vector<pair<int, int> >v[50001];
queue<int>h;
int t[50001], ct[50001];
bool viz[50001];
int main(){
int i, n, x, y, c, j, nod, newn, m, cost;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
fin>>n>>m;
for(i=1; i<=n; i++){
fin>>x>>y>>c;
v[x].push_back({y, c});
}
for(i=1; i<=n; i++) {
t[i]=1000000000;
}
h.push(1);
t[1]=0;
viz[1]=1;
ct[1]++;
int stop=0;
while(!h.empty()) {
nod=h.front();
for(j=0; j<v[nod].size(); j++) {
newn=v[nod][j].first;
cost=v[nod][j].second;
if(t[newn]>t[nod]+cost) {
t[newn]=t[nod]+cost;
if(viz[newn]==0) {
viz[newn]=1;
h.push(newn);
ct[newn]++;
if(ct[newn]>n){
fout<<"Ciclu negativ!";
stop=1;
}
}
}
}
h.pop();
viz[nod]=0;
}
if(stop==0) {
for(i=2;i<=n; i++) {
fout<<t[i]<<" ";
}
}
return 0;
}