Cod sursa(job #1623882)

Utilizator TrascaAndreiTrasca Andrei TrascaAndrei Data 1 martie 2016 22:29:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>

using namespace std;

const int N = 50001;
const char inf[] = "bellmanford.in";
const char outf[] = "bellmanford.out";
const int INF = 100000;

queue<int> q;
vector<int> a[N],c[N];
int n,m,d[N],w[N];

void bellman_ford()
{
    int i,j,x;
    for(i=2;i<=n;i++)
        d[i]=INF;
    q.push(1);
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        w[x]++;
        if(w[x]>n)
        {
            printf("Ciclu negativ!");
            return;
        }
        for(j=0;j<a[x].size();j++)
            if(d[x]+c[x][j]<d[a[x][j]])
            {
                d[a[x][j]]=d[x]+c[x][j];
                q.push(a[x][j]);
            }
    }
    for(i=2;i<=n;i++)
        printf("%d ",d[i]);
}

int main()
{
    freopen(inf,"r",stdin);
    freopen(outf,"w",stdout);
    int i,j,k,l,x;
    scanf("%d %d",&n,&m);
    for(l=1;l<=m;l++)
    {
        scanf("%d %d %d",&i,&j,&k);
        a[i].push_back(j);
        c[i].push_back(k);
    }
    bellman_ford();
    return 0;
}