Cod sursa(job #1650131)

Utilizator tudormaximTudor Maxim tudormaxim Data 11 martie 2016 16:46:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
using namespace std;

ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");

const int nmax = 5e4+5;
const int oo = (1<<30);
vector <pair<int,int> > g[nmax];
int dist[nmax], cnt[nmax], n;

bool bellman(int start)
{
    vector <pair<int,int> > :: iterator it;
    queue <int> q;
    bitset <nmax> viz=0;
    int dad, son, cost;
    fill(dist+1, dist+n+1, oo);
    dist[start]=0;
    q.push(start);
    while(!q.empty())
    {
        dad=q.front();
        viz[dad]=false;
        q.pop();
        for(it=g[dad].begin(); it!=g[dad].end(); it++)
        {
            son=it->first;
            cost=it->second;
            if(dist[son] > dist[dad]+cost)
            {
                dist[son]=dist[dad]+cost;
                if(viz[son]==false)
                {
                    viz[son]=true;
                    cnt[son]++;
                    q.push(son);
                    if(cnt[son] > n) return true;
                }
            }
        }
    }
    return false;
}

int main()
{
    ios_base::sync_with_stdio(false);
    int m, i, x, y, c;
    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        g[x].push_back(make_pair(y, c));
    }
    bool cycle=bellman(1);
    if(cycle==true) fout << "Ciclu negativ!";
    else for(i=2; i<=n; i++)
    {
        if(dist[i]==oo) dist[i]=0;
        fout << dist[i] << " ";
    }
    fin.close();
    fout.close();
    return 0;
}