Cod sursa(job #1412051)

Utilizator 4ONI2015oni2015 4ONI2015 Data 1 aprilie 2015 08:39:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define oo 1<<30
#define pb push_back
#define mp make_pair
#define N 50005

using namespace std;

vector<pair<int, int>>v[N];
int d[N], cnt[N], i, n, m, x, y, c, nod;
queue<int>q;
bitset<N>inq;

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(; m; m--)
    {
        scanf("%d%d%d", &x, &y, &c);
        v[x].pb(mp(y, c));
    }
    for(i = 2; i <= n; i++)
        d[i] = oo;
    q.push(1);
    inq[1] = 1;
    d[1] = 0;
    while(q.size())
    {
        nod = q.front();
        q.pop();
        inq[nod] = 0;
        for(auto it : v[nod])
            if(d[it.first] > d[nod] + it.second)
            {
                d[it.first] = d[nod] + it.second;
                if(inq[it.first])
                    continue;
                cnt[it.first]++;
                if(cnt[it.first]>n)
                {
                    printf("Ciclu negativ!");
                    return 0;
                }
                q.push(it.first);
                inq[it.first] = 1;
            }
    }
    for(i = 2; i <= n; i++)
        printf("%d ", d[i]);
    return 0;
}