Cod sursa(job #2631183)

Utilizator cyg_vladioanBirsan Vlad cyg_vladioan Data 29 iunie 2020 12:46:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int NMAX = 50000;
const int INF = 2.e9;
struct muchii
{
    int nod , cost;
    muchii(int x = 0 , int y = 0)
    {
        nod = x;
        cost = y;
    }
};
vector <muchii> G[NMAX + 5];
int d[NMAX + 5] , viz[NMAX + 5] , l[NMAX + 5] , n;
void init()
{
    for(int i = 2 ; i <= n ; i ++)
        d[i] = INF;
}
int bellmanford(int s)
{
    int j , u , v , c;
    init();
    queue <int> q;
    q.push(s);
    viz[s] = 1;
    while(!q.empty())
    {
        u = q.front();
        q.pop();
        viz[u] = 0;
        for(j = 0 ; j < G[u].size() ; j ++)
        {
            v = G[u][j].nod;
            c = G[u][j].cost;
            if(d[v] > d[u] + c)
            {
                if(l[u] == n - 1)
                    return 0;
                else
                {
                    d[v] = d[u] + c;
                    l[v] = l[u] + 1;
                    if(!viz[v])
                    {
                        viz[v] = 1;
                        q.push(v);
                    }
                }
            }
        }
    }
    return 1;
}
int main()
{
    freopen("bellmanford.in" , "r" , stdin);
    freopen("bellmanford.out" , "w" , stdout);
    int m , x , y , z , i , j , ok;
    scanf("%d%d" , &n , &m);
    for(i = 1 ; i <= m ; i ++)
    {
        scanf("%d%d%d" , &x , &y , &z);
        G[x].push_back(muchii(y , z));
    }
    if(bellmanford(1))
        for(i = 2 ; i <= n ; i ++)
            printf("%d " , d[i]);
    else
        printf("Ciclu negativ!\n");
    return 0;
}