Cod sursa(job #2166027)

Utilizator alexandra_paticaAndreea Alexandra Patica alexandra_patica Data 13 martie 2018 15:09:23
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

int n, i, m, x, y, c, d[100002], ciclu[100002];
vector<int>G[100002], C[100002];
queue<int>q;

int bellmanford (int x0)
{
    memset(d, 1, sizeof(d));
    d[x0]=0;
    q.push(x0);
    while (!q.empty()){
        x=q.front();
        q.pop();
        ciclu[x]++;
        if (ciclu[x]>n) return -1;
        for (i=0; i<G[x].size(); i++){
            if (d[G[x][i]]>d[x]+C[x][i]){
                d[G[x][i]]=d[x]+C[x][i];
                q.push(G[x][i]);
            }
        }
    }
    return 1;
}

int main ()
{

    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);

    scanf("%d%d", &n, &m);
    for (i=1; i<=m; i++){
        scanf("%d%d%d", &x, &y, &c);
        G[x].push_back(y);
        C[x].push_back(c);
    }


    c=bellmanford(1);
    if (c>0){
        for (i=2; i<=n; i++){
            printf("%d ", d[i]);
        }
    }
    else printf("Ciclu negativ!");
    return 0;
}