Cod sursa(job #1988763)

Utilizator Emy1337Micu Emerson Emy1337 Data 4 iunie 2017 16:53:55
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

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

const int maxN = 5e4+5;
vector<pair<int,int>> g[maxN];
priority_queue<pair<int,int>> coada;
unordered_map<int,bool> myHash;

int dist[maxN];

int main()
{
    int n, m;
    fin >> n >> m;
    while(m--)
    {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back({y,z});
    }

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

    dist[1] = 0;
    myHash[1] = true;
    for(int k=1; k<=n; k++)
    {
        for(int i=1; i<=n; i++)
        {
            if(myHash[i])
                if(dist[i] != INT_MAX)
                {
                    myHash[i] = false;
                    for(auto it: g[i])
                        if(dist[i] + it.second < dist[it.first]){
                            dist[it.first] = dist[i] + it.second;
                            myHash[it.first] = true;
                        }
                }
        }
    }

    for(int i=1; i<=n; i++)
    {
        if(dist[i] != INT_MAX)
        {
            for(auto it: g[i])
                if(dist[i] + it.second < dist[it.first])
                {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }
        }
    }



    for(int i=2; i<=n; i++)
        fout << dist[i] << " ";


    return 0;

}