Cod sursa(job #1566806)

Utilizator tc_iuresiures tudor-cristian tc_iures Data 12 ianuarie 2016 17:21:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int Nmax = 50005;
const int INF  = 2000000000;

vector< pair<int,int> > G[Nmax];
int N, M;
int D[Nmax], nrInQ[Nmax];
bool isInQ[Nmax], negativeCycles;

void read()
{
    ifstream f("bellmanford.in");
    f >> N >> M;
    for(int i = 0; i < M; i ++)
    {
        int x, y, z;
        f >> x >> y >> z;
        G[x].push_back(make_pair(y,z));
    }
    f.close();
}

void solve()
{
    for(int i = 1; i <= N; i ++)
    {
        D[i] = INF;
    }
    isInQ[1] = true;
    nrInQ[1]= 1;
    D[1] = 0;
    queue<int> Q;
    Q.push(1);
    while(!Q.empty() && !negativeCycles)
    {
        int Nod = Q.front();
        Q.pop();
        isInQ[Nod] = false;
        for(int i = 0; i < G[Nod].size(); i ++)
        {
            int Ngh = G[Nod][i].first;
            if(D[Ngh] > D[Nod] + G[Nod][i].second)
            {
                D[Ngh] = D[Nod] + G[Nod][i].second;
                if(!isInQ[Ngh])
                {
                    if(nrInQ[Ngh] > N)
                    {
                        negativeCycles = true;
                    }
                    else
                    {
                        isInQ[Ngh] = true;
                        nrInQ[Ngh] ++;
                        Q.push(Ngh);
                    }
                }
            }
        }
    }
}

void print()
{
    ofstream g("bellmanford.out");
    if(negativeCycles)
    {
        g << "Ciclu negativ!";
    }
    else
    {
        for(int i = 2; i <= N; i ++)
        {
            g << D[i] << " ";
        }
    }
    g.close();
}

int main()
{
    read();
    solve();
    print();
    return 0;
}