Cod sursa(job #1496045)

Utilizator UMihneaUngureanu Mihnea UMihnea Data 4 octombrie 2015 10:31:16
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <cstdio>
#include <vector>
#include <queue>
#define N 50010
#define oo 100000000

using namespace std;

vector<pair<int, int> > v[N];
int cost[N], q[N], viz[N], n, m, i, x, y, z ;
queue<int> Q;

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,&z);
        v[x].push_back(make_pair(y,z));
    }

    for(i=1;i<=n;i++)
        cost[i] = oo;

    cost[1] = 0;
    q[1] = 1;
    Q.push(1);

    while(Q.size())
    {
        x = Q.front(); Q.pop();
        q[x] = 0;
        for(auto it:v[x])
        {
            if(cost[it.first]<=cost[x]+it.second)
                continue;
            cost[it.first] = cost[x]+it.second;
            if(!q[it.first])
            {
                viz[it.first]++;
                if(viz[it.first] == n)
                {
                    printf("Ciclu negativ!\n");
                    return 0;
                }
                q[it.first] = 1;
                Q.push(it.first);
            }
        }
    }

    for(i=2;i<=n;i++)
        printf("%d ",cost[i]);

    return 0;
}