Pagini recente » Cod sursa (job #714214) | Cod sursa (job #2486701) | Cod sursa (job #2359965) | Cod sursa (job #354258) | Cod sursa (job #2126077)
#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 x, y, cost;
FILE *fin = fopen("bellmanford.in","r");
fscanf(fin,"%d%d",&n,&m);
for(int i = 0; i < m; i++) {
fscanf(fin,"%d%d%d",&x,&y,&cost);
g[x].push_back(make_pair(y,cost));
}
fclose(fin);
}
void BellmanFord(int source) {
vector<pair<int,int>>::iterator it;
int i, node;
for(i = 1; i <= n; i++)
dist[i] = oo;
dist[source] = 0;
q.push(source);
used[source] = true;
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");
if(cycle)
fprintf(fout,"Ciclu negativ!\n");
else {
for(int i = 2; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
}
fclose(fout);
}
int main() {
readGraph();
BellmanFord(1);
printDistances();
return 0;
}