Cod sursa(job #2103752)

Utilizator maria_sinteaMaria Sintea maria_sintea Data 10 ianuarie 2018 19:28:41
Problema Algoritmul Bellman-Ford Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
#define N 50005

using namespace std;

vector <pair<int, int> > graf[N];
queue <int> q;
int cost[N], n, m, a, b, c, viz[N];

void citire()
{
    scanf("%d %d\n", &n, &m);
    for(int i=1;i<=m;i++)
    {
        cost[i]=0x3f3f3f;
        scanf("%d %d %d", &a, &b, &c);
        graf[a].push_back(make_pair(b, c));
    }
}

void parcurg(int x)
{
    for(vector <pair<int, int> > :: iterator it=graf[x].begin();it!=graf[x].end();it++)
    {
        if(cost[x]+it->second<cost[it->first])
        {
            cost[it->first]=cost[x]+it->second;
            q.push(it->first);
        }
    }
}

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

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

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