Cod sursa(job #794247)

Utilizator alexalbu95Albu Alexandru alexalbu95 Data 6 octombrie 2012 00:10:32
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int maxn=50005;
const int inf=260000000;
vector< pair<int, int> > :: iterator it;

int n, m, d[maxn], x, cnt_inq[maxn], i;
bool block[maxn], inq[maxn], bad;
vector< pair<int, int> > v[maxn];
queue<int> q;

void read()
{
    int a, b, c;
    f>>n;
    for(f>>m; m; --m)
    {
        f>>a>>b>>c;
        v[a].push_back(make_pair(b, c));
    }
}

int bellmanford()
{
    d[1]=0;
    q.push(1);
    block[1]=1;

    while(!q.empty())
    {
        x=q.front();
        q.pop();

        for(it=v[x].begin(); it!=v[x].end(); ++it)
            if(d[it->first] > d[x] + it->second)
            {
                d[it->first] = d[x] + it->second;
                if(!inq[it->first])
                {
                    if(cnt_inq[it->first]>n) return 0;
                    else
                    {
                        q.push(it->first);
                        inq[it->first]=1;
                        cnt_inq[it->first]++;
                    }
                }
            }
    }
    return 1;
}
int main()
{
    read();
    for(i=1; i<=n; ++i) d[i]=inf;


    if(bellmanford())
        for(i=2; i<=n; ++i) g<<d[i]<<" ";
    else g<<"Ciclu negativ!";
}