Pagini recente » Cod sursa (job #491303) | Cod sursa (job #3172509) | Cod sursa (job #827147) | Cod sursa (job #1817136) | Cod sursa (job #2171598)
#include<cstdio>
#include<queue>
#include<vector>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;
vector< pair<int, int> >g[MAX_N + 1];
queue<int>q;
int d[MAX_N + 1], vizNode[MAX_N + 1], n, m;
bool used[MAX_N + 1], cycle;
void readGraph() {
int x, y, c;
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,&c);
g[x].push_back(make_pair(y,c));
}
fclose(fin);
}
void bellmanFord(int Node) {
vector<pair <int, int> > ::iterator it;
int i, node;
for(i = 1; i <= n; i++)
d[i] = oo;
d[Node] = 0;
q.push(Node);
used[Node] = true;
while(!q.empty() && !cycle) {
node = q.front();
q.pop();
used[node] = false;
for(it = g[node].begin(); it != g[node].end(); it++) {
if(d[(*it).first] > d[node] + (*it).second) {
d[(*it).first] = d[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 ",d[i]);
fprintf(fout,"\n");
}
fclose(fout);
}
int main() {
readGraph();
bellmanFord(1);
printDistances();
return 0;
}