Pagini recente » Cod sursa (job #542237) | Cod sursa (job #2208111) | Cod sursa (job #1097672) | Cod sursa (job #431498) | Cod sursa (job #2211038)
#include<cstdio>
#include<vector>
#include<queue>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;
vector<pair<int,int> >g[MAX_N+1];
queue<int>q;
int dist[MAX_N+1], vizNode[MAX_N+1], n, m;
bool used[MAX_N+1], cycle;
void readGraph() {
int i, x, y, c;
FILE* fin = fopen("bellmanford.in","r");
fscanf(fin,"%d%d",&n,&m);
for(i = 0; i < m; i++) {
fscanf(fin,"%d%d%d",&x,&y,&c);
g[x].push_back(make_pair(y,c));
}
fclose(fin);
}
void BellmanFord(int source) {
int i, node;
vector<pair<int,int> >::iterator it;
for(i = 1; i <= n; i++)
dist[i] = oo;
dist[source] = 0;
used[source] = true;
q.push(source);
while(!q.empty() && !cycle) {
node = q.front();
q.pop();
used[node] = false;
for(it = g[node].begin(); it != g[node].end(); it++) {
if(dist[(*it).first] > dist[node] + (*it).second) {
dist[(*it).first] = dist[node] + (*it).second;
if(!used[(*it).first]) {
q.push((*it).first);
used[(*it).first] = true;
if(++vizNode[(*it).first] > n)
cycle = true;
}
}
}
}
}
void printDistances() {
FILE* fout = fopen("bellmanford.out","w");
BellmanFord(1);
if(!cycle) {
for(int i = 2; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
} else fprintf(fout,"Ciclu negativ!\n");
fclose(fout);
}
int main() {
readGraph();
printDistances();
return 0;
}