Cod sursa(job #887112)

Utilizator gegeadDragos Gegea gegead Data 23 februarie 2013 15:37:45
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in ("bellmanford.in");
ofstream out("bellmanford.out");
int const N=50005;
int const MAXI=100000;
vector <int> v[N],c[N];
bool inq[N];
int n,m,cost[N],nrq[N];
void citire()
{
    in>>n>>m;
    int x,y,z;
    for(int i=1;i<=m;i++)
    {
        in>>x>>y>>z;
        v[x].push_back(y);
        c[x].push_back(z);
    }
}
void init()
{
    for(int i=2;i<=n;i++)
        cost[i]=MAXI;
}
bool bfs(int x)
{
    queue <int> q;
    q.push(x);
    inq[x]=true;
    nrq[x]++;
    int y,z;
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        inq[x]=false;
        for(int i=0;i<v[x].size();i++)
        {
            y=v[x][i];  z=c[x][i];
            if(cost[y]>cost[x]+z)
            {
                cost[y]=cost[x]+z;
                if(!inq[y])
                {
                    q.push(y);
                    inq[y]=true;
                    nrq[y]++;
                    if(nrq[y]==n)   return true;
                }
            }
        }
    }
    return false;
}
int main()
{
    citire();
    init();
    if(bfs(1)){out<<"Ciclu negativ!\n";return 0;}
    for(int i=2;i<=n;i++)
        out<<cost[i]<<" ";
    out<<"\n";
    return 0;
}