Cod sursa(job #1922353)

Utilizator dragomirmanuelDragomir Manuel dragomirmanuel Data 10 martie 2017 17:05:19
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int NMax = 50005;
const int MMax = 250005;
const int inf = 0x3f3f3f3f;

int N, M;
int dist[NMax], viz[NMax];

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

void Read()
{
    scanf("%d%d", &N, &M);

    for(int i=1; i<=M; ++i)
    {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);

        G[x].push_back(make_pair(y,c));

    }

    for(int i=2; i<=N; ++i)
        dist[i] = inf;
}

void BellFord()
{
    Q.push(1);
    dist[1]=0;

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

        vector < pair < int, int > > ::iterator it;

        for(it=G[nod].begin(); it!=G[nod].end(); ++it)
        {
            if(dist[it->first] > it->second + dist[nod])
            {
                dist[it->first] = dist[nod] + it->second;
                viz[it->first]++;

                if(viz[it->first] > N)
                {
                    printf("Ciclu negativ!");
                    return;
                }

                Q.push(it->first);
            }
        }
    }

    for(int i=2; i<=N; ++i)
        printf("%d ", dist[i]);
}

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

    Read();
    BellFord();

    return 0;
}