Cod sursa(job #2126129)

Utilizator B_RazvanBaboiu Razvan B_Razvan Data 9 februarie 2018 11:19:41
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#define INF 0x3f3f3f
#define NMAX 50005

using namespace std;

int N, M, dist[NMAX], nrTreceri[NMAX];
vector <pair <int, int> > G[NMAX];
vector <pair <int, int> >::iterator it;
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;
}

bool bellmanFord()
{
    Q.push(1);
    while(!Q.empty())
    {
        int nod = Q.front();
        Q.pop();
        for(it = G[nod].begin(); it != G[nod].end(); ++it)
            if(dist[it->first] > dist[nod] + it->second)
            {
                dist[it->first] = dist[nod] + it->second;
                nrTreceri[it->first]++;
                if(nrTreceri[it->first] > N)
                    return false;
                Q.push(it->first);
            }
    }
    return true;
}

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

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    read();
    if(bellmanFord())
        print();
    else
        printf("Ciclu negativ!");
    return 0;
}