Cod sursa(job #1571215)

Utilizator trutruvasilicaHuhurez Marius trutruvasilica Data 17 ianuarie 2016 15:40:07
Problema Deque Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int N=50001,inf=0x3f3f3f3f;
struct nod
{
    int next,cost;
}pas;
vector<nod>H[N];
queue<int>Q;
int nr[N],dist[N];
int main()
{
    int n,m,i,a,b,c,ok=0;
    memset(dist,inf,sizeof(dist));
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>a>>pas.next>>pas.cost;
        H[a].push_back(pas);
    }
    Q.push(1);
    nr[1]=1;dist[1]=0;
    while(Q.size())
    {
        a=Q.front();
        Q.pop();
        for(vector<nod>::iterator it=H[a].begin();it!=H[a].end();it++)
        {
            if(dist[it->next]>dist[a]+it->cost)
            {
                dist[it->next]=dist[a]+it->cost;
                nr[it->next]++;
                Q.push(it->next);
                if(nr[it->next]>n) ok=1;
            }
        }
        if(ok==1) break;
    }
    if(ok==1) fout<<"Ciclu negativ!";
    else
    {
        for(i=2;i<=n;i++)
        {
            if(dist[i]!=inf) fout<<dist[i]<<" ";
            else fout<<"0 ";
        }
    }
}