Cod sursa(job #2349289)

Utilizator Horia14Horia Banciu Horia14 Data 20 februarie 2019 12:46:09
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include<cstdio>
#include<vector>
#include<queue>
#include<cctype>
#define MAX_N 50000
#define oo 0x3f3f3f3f
#define BUF_SIZE 1 << 17
using namespace std;

vector<pair<int,int> >g[MAX_N+1];
queue<int>q;
int dist[MAX_N+1], nrViz[MAX_N+1], n, m, pos = BUF_SIZE;
bool used[MAX_N+1], cycle;
char buf[BUF_SIZE];

inline char getChar(FILE* fin) {
    if(pos == BUF_SIZE) {
        fread(buf,1,BUF_SIZE,fin);
        pos = 0;
    }
    return buf[pos++];
}

inline int read(FILE* fin) {
    int res, semn;
    char ch;
    semn = 1, res = 0;
    do {
        ch = getChar(fin);
        if(ch == '-')
            semn = -semn;
    }while(!isdigit(ch));
    do {
        res = 10*res + ch - '0';
        ch = getChar(fin);
    }while(isdigit(ch));
    return res*semn;
}

void readGraph() {
    int x, y, c, i;
    FILE* fin = fopen("bellmanford.in","r");
    n = read(fin);
    m = read(fin);
    //printf("%d %d\n",n,m);
    for(i = 1; i <= m; i++) {
        x = read(fin);
        y = read(fin);
        c = read(fin);
        g[x].push_back(make_pair(y,c));
        //printf("%d %d %d\n",x,y,c);
    }
    fclose(fin);
}

void bellmanFord(int x) {
    int node;
    vector<pair<int, int> >::iterator it;
    for(int i = 1; i <= n; i++) {
        dist[i] = oo;
        used[i] = false;
    }
    dist[x] = 0;
    q.push(x);
    used[x] = true;
    cycle = false;
    while(!q.empty() && !cycle) {
        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]) {
                    used[(*it).first] = true;
                    q.push((*it).first);
                    if(++nrViz[(*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 ",dist[i]);
        fprintf(fout,"\n");
    }
    fclose(fout);
}

int main() {
    readGraph();
    bellmanFord(1);
    printDistances();
    return 0;
}