Cod sursa(job #1690523)

Utilizator Mr.RobotElliot Alderson Mr.Robot Data 15 aprilie 2016 11:12:41
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

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

#define mult 1000000000

vector<pair<int,int> > liste[50001];
vector<pair<int,pair<int,int> > > muc;
int n, m, x, y, z, t[50001], dist[50001], nod, distanta;


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

    bool neg = false;

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

    for( int i=1; i<=n; i++ )
        dist[i] = mult;
    dist[1] = 0;

    queue<pair<int,int> > q;

    q.push(make_pair(1,0));

    while( !q.empty() && neg == false )
    {
        nod = q.front().first;
        distanta = q.front().second;

        q.pop();

        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;
                q.push( make_pair( it->first, dist[it->first ]));
                t[it->first]++;
                if( t[it->first] > n -1)
                    neg = true;
            }
    }
    if( neg)
    {
        out << "Circuit negativ!";
        return 0;
    }
    for( int i=2; i<=n; i++ )
        out << dist[i] << " ";
}