Cod sursa(job #2353500)

Utilizator maria_sinteaMaria Sintea maria_sintea Data 24 februarie 2019 12:41:15
Problema Algoritmul Bellman-Ford Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <cstdio>
#include <queue>
#define inf 0x3f3f3f3f
#define N 50005

using namespace std;

int n, m, cost[N], viz[N];
struct nod
{
    int y, c;
};
vector <nod> g[N];
vector <nod> ::iterator it;
queue <int> q;

void citire()
{
    scanf("%d %d\n", &n, &m);
    for(int i=0;i<m;i++)
    {
        int xx, yy, cc;
        cost[i]=inf;
        scanf("%d %d %d\n", &xx, &yy, &cc);
        g[xx].push_back({yy, cc});
    }
}

void parcurg(int x)
{
    for(it=g[x].begin();it!=g[x].end();it++)
        if(cost[it->y]>cost[x]+it->c)
        {
            cost[it->y]=cost[x]+it->c;
            q.push(it->y);
        }
}

void afisare()
{
    for(int i=2;i<=n;i++)
        printf("%d ", cost[i]);
}

void bellman()
{
    q.push(1);
    cost[1]=0;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        if(viz[x]==n)
        {
            printf("Ciclu negativ!");
            return;
        }
        viz[x]++;
        parcurg(x);
    }
    afisare();
}

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

    citire();
    bellman();
    return 0;
}