Cod sursa(job #1690359)

Utilizator Mr.RobotElliot Alderson Mr.Robot Data 15 aprilie 2016 01:06:17
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

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

#define mult 9000000000

vector<pair<int,pair<int,int> > > muchii;
vector<pair<int,int> > liste[50001], heap;
int n, m, x, y, z, viz[50001];
long long dist[50001];


void solve()
{
    int nod, distanta;

    int pas = 0;

    for( int i=2; i<=n; i++ )
        dist[i]=mult;
    dist[1] = 0;
    heap.push_back( make_pair(0,1));
    make_heap( heap.begin(), heap.end());
    while ( !heap.empty() && pas <= n*m )
    {

        pas++;

        pop_heap( heap.begin(), heap.end() );

        nod = heap.back().second;
        distanta = -(heap.back().first);

        heap.pop_back();

        viz[nod] = 0;

        for( vector<pair<int,int> >::iterator it = liste[nod].begin(); it!=liste[nod].end(); it++ )
        {
            if( dist[it->first] > distanta + it->second )
            {
                dist[it->first] = distanta + it->second;
                if( viz[it->first] == 0 )
                {
                    viz[it->first] = 1;
                    heap.push_back(make_pair(-dist[it->first],it->first));
                    push_heap(heap.begin(), heap.end());
                }
            }
        }
    }

}

int ciclu()
{
    for( vector<pair<int, pair<int,int> > >::iterator it=muchii.begin(); it!=muchii.end(); it++ )
        if( dist[it->second.second] > it->first + dist[it->second.first])
            return 1;
    return 0;
}

int main()
{
    in >> n >> m;

    for( int i=1; i<=m; i++ )
    {
        in >> x >> y >> z;
        muchii.push_back(make_pair(z,make_pair(x,y)));
        liste[x].push_back(make_pair(y,z));
    }

    solve();
    if( ciclu() )
    {
        out << "Ciclu negativ!";
    }
    else
    {
        for( int i=2; i<=n; i++ )
            out << dist[i] << " ";
    }
    return 0;
}