Pagini recente » Cod sursa (job #963234) | Cod sursa (job #533754) | Cod sursa (job #1337939) | Cod sursa (job #2326222) | Cod sursa (job #2046958)
#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;
bool used[MAX_N+1];
int dist[MAX_N+1], nrv[MAX_N+1], n, m;
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);
}
bool bellmanFord(int x) {
int i, node;
bool ok;
vector<pair<int,int>>::iterator it;
for(i=1; i<=n; i++)
dist[i] = oo;
dist[x] = 0;
Q.push(x);
used[x] = true;
ok = false;
while(!Q.empty() && !ok) {
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]) {
if(++nrv[(*it).first] > n)
ok = true;
else {
Q.push((*it).first);
used[(*it).first] = true;
}
}
}
}
return ok;
}
void printDistances() {
FILE *fout = fopen("bellmanford.out","w");
if(!bellmanFord(1)) {
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;
}