Cod sursa(job #2232380)

Utilizator Horia14Horia Banciu Horia14 Data 18 august 2018 21:24:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#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;
}