Cod sursa(job #1690559)

Utilizator Mr.RobotElliot Alderson Mr.Robot Data 15 aprilie 2016 11:44:27
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 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;
bool in_q[50001];

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<int> q;

    q.push(1);
    t[1]++;
    in_q[1] = true;

    while( !q.empty())
    {
        nod = q.front();
        in_q[nod] = false;
        q.pop();

        for( vector<pair<int,int> >::iterator it = liste[nod].begin(); it!=liste[nod].end(); it++ )
            if( dist[it->first] > dist[nod] + it->second )
            {
                dist[it->first] = it->second + dist[nod];
                if( !in_q[it->first] )
                {
                    q.push( it->first);
                    t[it->first]++;
                    in_q[it->first] = true;
                    if( t[it->first] > n )
                    {
                            neg = true;
                            out << "Ciclu negativ!";
                            return 0;
                    }
                }
            }
    }
    if( neg)
    {
        out << "Circuit negativ!";
        return 0;
    }
    for( int i=2; i<=n; i++ )
        out << dist[i] << " ";
}