Pagini recente » Cod sursa (job #1059474) | Cod sursa (job #216757) | Cod sursa (job #1821608) | Cod sursa (job #44314) | Cod sursa (job #2362409)
#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, c, i;
FILE* fin = fopen("bellmanford.in","r");
fscanf(fin,"%d%d",&n,&m);
for(i = 1; i <= m; i++) {
fscanf(fin,"%d%d%d",&x,&y,&c);
g[x].push_back(make_pair(y,c));
//printf("%d %d %d\n",x,y,c);
}
fclose(fin);
}
void bellman(int source) {
int node;
for(int i = 1; i <= n; i++) {
dist[i] = oo;
vizNode[i] = used[i] = 0;
}
dist[source] = 0;
q.push(source);
used[source] = true;
cycle = false;
while(!q.empty() && !cycle) {
node = q.front();
q.pop();
used[node] = false;
for(auto i : g[node]) {
if(dist[i.first] > dist[node] + i.second) {
dist[i.first] = dist[node] + i.second;
if(!used[i.first]) {
q.push(i.first);
used[i.first] = true;
if(++vizNode[i.first] > n)
cycle = true;
}
}
}
}
}
void printDistances() {
int i;
FILE* fout = fopen("bellmanford.out","w");
if(cycle)
fprintf(fout,"Ciclu negativ!\n");
else {
for(i = 2; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
}
fclose(fout);
}
int main() {
readGraph();
bellman(1);
printDistances();
return 0;
}