Pagini recente » Cod sursa (job #1625584) | Cod sursa (job #1794737) | Cod sursa (job #69021) | Cod sursa (job #673787) | Cod sursa (job #933318)
Cod sursa(job #933318)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
#include <deque>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#define nmax 50005
#define ll long long
#define inf (1<<30)
int n, m, viz[nmax], dist[nmax];
vector< pair<int,int> > gf[nmax];
bool inCoada[nmax];
queue<int> q;
void citeste(){
f >> n >> m;
int x, y, z;
for(int i=1; i<=m; ++i){
f >> x >> y >> z;
gf[x].push_back( make_pair(y, z) );
}
}
void rezolva(){
for(int i=1;i <=n; ++i) dist[i] = inf;
q.push(1); inCoada[1] = 1;
dist[1] = 0;
for(; q.size(); ){
int nod = q.front(); q.pop();
inCoada[nod] = 0;
for(int i=0; i<gf[nod].size(); ++i){
int vc = gf[nod][i].first;
int cost = gf[nod][i].second;
if (dist[vc] > dist[nod] + cost){
dist[vc] = dist[nod] + cost;
if (inCoada[vc] == 0){
if (viz[vc] > n){
g << "Ciclu negativ!" << "\n";
return;
}
++viz[vc]; inCoada[vc] = 1; q.push(vc);
}
}
}
}
for(int i=2; i<=n; ++i) g << dist[i] << " ";
g << "\n";
}
int main(){
citeste();
rezolva();
f.close();
g.close();
return 0;
}