Pagini recente » Cod sursa (job #1996229) | Cod sursa (job #641024) | Cod sursa (job #996717) | Cod sursa (job #637472) | Cod sursa (job #2232380)
#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], cnt[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 s) {
int j, node;
for(j = 1; j <= n; j++) {
dist[j] = oo;
used[j] = false;
}
dist[s] = 0;
q.push(s);
used[s] = 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(++cnt[i.first] > n)
cycle = true;
}
}
}
}
}
void printDistances() {
FILE* fout = fopen("bellmanford.out","w");
if(!cycle)
for(int i = 2; i <= n; i++)
fprintf(fout,"%d ",dist[i]);
else fprintf(fout,"Ciclu negativ!");
fprintf(fout,"\n");
fclose(fout);
}
int main() {
readGraph();
bellmanFord(1);
printDistances();
return 0;
}