Cod sursa(job #2135860)

Utilizator inquisitorAnders inquisitor Data 19 februarie 2018 13:15:18
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <cstdio>
#include <queue>
#include <algorithm>
#define inf 1000000000
#define bufs 1000000
#define nxt() {pos++;\
    if(pos >= bufs)\
    {\
        fread(buf, 1, bufs, stdin);\
        pos = 0;\
    }\
}

using namespace std;

vector< pair<int, int> > g[50000];
int n, m;
queue<int> q;
bool viz[50000] = {0};
int nr[50000] = {0};
int dist[50000];

char buf[bufs];
int pos = bufs;
int neg;

inline void read(int& val)
{
    neg = 0;
    while((buf[pos] < '0' || buf[pos] > '9') && buf[pos] != '-') nxt();
    if(buf[pos] == '-') { neg = 1; val = 0; }
    else val = buf[pos] - '0';
    nxt();
    while(buf[pos] >= '0' && buf[pos] <= '9') { val = val * 10 + buf[pos] - '0'; nxt(); }
    if(neg == 1) val = -val;
}

int main()
{
    int i, j, a, b, c;
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    read(n); read(m);
    for(i = 0; i < m; i++)
    {
        read(a); read(b); read(c);
        a--; b--;
        g[a].push_back(make_pair(b, c));

    }
    for(i = 1; i < n; i++)
        dist[i] = inf;
    q.push(0);
    nr[0] = 1;
    while(!q.empty())
    {
        a = q.front();
        q.pop();
        viz[a] = 0;
        for(i = 0; i < g[a].size(); i++)
        {
            if(dist[g[a][i].first] > dist[a] + g[a][i].second)
            {
                dist[g[a][i].first] = dist[a] + g[a][i].second;
                if(viz[g[a][i].first] == 0)
                {
                    viz[g[a][i].first] = 1;
                    q.push(g[a][i].first);
                    nr[g[a][i].first]++;
                    if(nr[g[a][i].first] >= n)
                    {
                        printf("Ciclu negativ!");
                        return 0;
                    }
                }
            }
        }
    }
    for(i = 1; i < n; i++)
    {
        printf("%d ", dist[i]);
    }
    return 0;
}