Cod sursa(job #1119109)

Utilizator vasandANDREI POP vasand Data 24 februarie 2014 15:21:57
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
# include <string.h>
# define nmax 50000
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmabford.out");

int dist[nmax], apar[nmax], n, m;
queue <int> q;
vector < pair <int, int> > a[nmax];
bool inq[nmax];

int main()
{
    int i, x, y, c;

    f>>n>>m;
    for(i=1; i<=m; i++)
    {
        f>>x>>y>>c;
        a[x].push_back(make_pair(y,c));
    }

    memset(dist, '5', sizeof(dist));
    memset(inq, false, sizeof(inq));

    dist[1]=0;
    q.push(1);

    int nod;
    bool neg_cycle=false;
    vector < pair <int, int> > :: iterator it;

    while(!q.empty())
    {
        nod=q.front();
        q.pop();
        inq[nod]=false;
        for(it=a[nod].begin(); it!=a[nod].end(); ++it)
        {
            if(dist[it->first] > dist[nod] + it->second)
            {
                dist[it->first] = dist[nod] + it->second;
                if(!inq[it->first])
                {
                    if(apar[it->first] > n)
                    {
                        neg_cycle=true;
                        break;
                    }
                    else
                    {
                        q.push(it->first);
                        apar[it->first]+=1;
                        inq[it->first]=true;
                    }
                }
            }
        }
    }

    if(neg_cycle)
        cout<<"Ciclu negativ!";
    else
    {
        for(i=2; i<=n; i++)
            cout<<dist[i]<<" ";
    }

    return 0;
}