Cod sursa(job #2282246)

Utilizator petru.ciocirlanPetru Ciocirlan petru.ciocirlan Data 13 noiembrie 2018 15:23:04
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;

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

const int MAX_N = 50000 + 16;
const int MAX_M = 250000 + 16;
const int INF = 0x3f3f3f3f;

int N, M;
int Dist[MAX_N];
vector < pair < int, int > > Edges[MAX_N];

int TimesVisited[MAX_N];
bool IsInQueue[MAX_N];
queue < int > Q;

bool BellmanFord(int start)
{
    memset(Dist+1, INF, N * sizeof(int));
    Dist[start] = 0;
    Q.push(start);

    while(!Q.empty())
    {
        int top = Q.front();
        Q.pop();
        TimesVisited[top]++;

        if(TimesVisited[top] >= N)
            return false;

        IsInQueue[top] = false;

        vector < pair < int, int > > :: iterator it;
        for(it = Edges[top].begin(); it != Edges[top].end(); ++it)
        {
            if(Dist[it->first] > Dist[top] + it->second)
            {
                Dist[it->first] = Dist[top] + it->second;

                if(!IsInQueue[it->first])
                {
                    Q.push(it->first);
                    IsInQueue[it->first] = true;
                }
            }
        }
    }

    return true;
}

int main()
{
    fin >> N >> M;
    for(int a, b, c, i = 1; i <= M; ++i)
    {
        fin >> a >> b >> c;
        Edges[a].push_back(make_pair(b, c));
    }

    if(BellmanFord(1))
    {
        for(int i = 2; i <= N; ++i)
            fout << Dist[i] << ' ';
    }
    else
        fout << "Ciclu negativ!\n";

    return 0;
}