Cod sursa(job #1072582)

Utilizator StickmanLazar Alexandru Stickman Data 4 ianuarie 2014 17:01:19
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

vector < long int> v[50002];
long int n,m,cost[50002],x,y,c,a,nr[50001];
queue <long int> q;

int blf()
{
    int i, top=1,a;
    while(!q.empty())
    {
        a=q.front();
        for(int k=0; k<v[a].size(); k+=2)
        {

            if(cost[v[a][k]]>cost[a]+v[a][k+1])
            {
                q.push(v[a][k]);
                nr[v[a][k]]++;
                cost[v[a][k]]=cost[a]+v[a][k+1];

            }
            if(nr[v[a][k]]>=n)
                return 0;
        }
        q.pop();
    }
    return 1;
}

int main()
{
    ifstream in("bellmanford.in");
    ofstream out("bellmanford.out");
    in>>n>>m;
    for(int i=0; i<m; i++)
    {
        in>>x>>y>>c;
        v[x].push_back(y);
        v[x].push_back(c);

    }
    in.close();
    for(int i=2; i<=n; i++)
    {
        cost[i]=9999999;
    }
    q.push(1);
     int ok=blf();
     if(!ok)
        out<<"Ciclu negativ!";
     else
    for(int i=2; i<=n; i++)
    {
        out<<cost[i]<<" ";
    }
    out.close();
    return 0;
}