Cod sursa(job #1929435)

Utilizator mihai.alphamihai craciun mihai.alpha Data 17 martie 2017 17:12:46
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <vector>
#include <queue>

using namespace std;

FILE *fin = fopen("bellmanford.in", "r"), *fout = fopen("bellmanford.out", "w");

#define BUF 1 << 17
int pos = BUF;
char buf[BUF];

inline char next()  {
    if(pos == BUF)
        fread(buf, 1, BUF, fin), pos = 0;
    return buf[pos++];
}

inline int read()  {
    int x = 0, semn = 1;
    char ch = next();
    while(!isdigit(ch) && ch != '-')
        ch = next();
    if(ch == '-')
        semn = -1, ch = next();
    while(isdigit(ch))
        x = x * 10 + ch - '0', ch = next();
    return x * semn;
}

struct atom  {
    int nod;
    int cost;
};

#define NMAX 50000

vector <atom> v[NMAX + 1];
int d[NMAX + 1];/* costurile */
int w[NMAX + 1];/* de cate ori a aparut nodul */
int N, M;

inline void bellman(int nod)  {
    queue <int> q;
    q.push(nod);
    d[nod] = 0;
    while(!q.empty())  {
        int el = q.front();
        w[el]++;
        if(w[el] > N)  {
            fputs("Ciclu negativ!\n", fout);
            return;
        }
        for(unsigned int i = 0;i < v[el].size();i++)  {
            int uau = v[el][i].nod;
            int cost = v[el][i].cost;
            if(d[el] + cost < d[uau])  {
                d[uau] = d[el] + cost;
                q.push(uau);
            }
        }
        q.pop();
    }
    for(int i = 2;i <= N;i++)
        fprintf(fout, "%d ", d[i]);
    fputc('\n', fout);
}

int main()  {
    N = read(), M = read();
    for(int i = 1;i <= M;i++)  {
        int x, y, c;
        x = read(), y = read(), c = read();
        v[x].push_back({y, c});
    }
    for(int i = 1;i <= N;i++)
        d[i] = INT_MAX;
    bellman(1);
    fclose(fin);
    fclose(fout);
    return 0;
}