Cod sursa(job #1688153)

Utilizator Mr.RobotElliot Alderson Mr.Robot Data 13 aprilie 2016 12:05:09
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 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;
long long dist[50001];


void solve()
{
    for( int i=1; i<=n; i++ )
        dist[i]=mult;
    dist[1] = 0;
    heap.push_back( make_pair(0,1));
    make_heap(heap.begin(),heap.end());

    for( int i=1; i<n; i++ )
    { //DENISA
        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] )
            {
                dist[it->second.second] = it->first + dist[it->second.first];
            }
    }
}

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));
        liste[y].push_back(make_pair(x,z));
    }

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