Cod sursa(job #876462)

Utilizator TeodoraTanaseTeodora Tanase TeodoraTanase Data 11 februarie 2013 20:47:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <cstdio>
#include <vector>
#include <queue>

#define NMAX 50001
#define INF (1 << 30)

using namespace std;

vector < pair <int, int> > G[NMAX];
queue <int> Q;

int n;
int d[NMAX];
int viz[NMAX];

void read()
{
    freopen("bellmanford.in", "r", stdin);

    int m;
    int x;
    int y;
    int c;

    scanf("%d %d", &n, &m);
    while(m --)
    {
        scanf("%d %d %d\n", &x, &y, &c);
        G[x].push_back(make_pair(y, c));
    }
}

int solve(int v)
{
    for(int i = 1; i <= n; d[i] = INF, ++ i);
    d[v] = 0;

    Q.push(v);

    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();

        unsigned int m = G[x].size();
        for(unsigned int i = 0; i < m; ++ i)
        {
            int y = G[x][i].first;
            int c = G[x][i].second;

            if(d[y] > d[x] + c)
            {
                d[y] = d[x] + c;
                Q.push(y);
                ++ viz[x];
            }
        }

        if(viz[x] > n)
            return 0;
    }

    return 1;
}

void write()
{
    freopen("bellmanford.out", "w", stdout);

    for(int i = 2; i <= n; ++ i)
        if(d[i] != INF)
            printf("%d ", d[i]);
        else
            printf("0 ");

    printf("\n");
}

int main()
{
    read();
    if(solve(1))
        write();
    else
        printf("Ciclu negativ!\n");

    return 0;
}