Cod sursa(job #2400866)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 9 aprilie 2019 10:46:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define INF 100000005
using namespace std;
struct muchie
{
    int nod;
    int cost;
}aux, aux1;
int n, m, i, x, y, c, d[50005], used[50005];
struct cmp
{
    bool operator()(muchie i, muchie j)
    {
        return i.cost > j.cost;
    }
};
priority_queue<muchie, vector<muchie>, cmp> hip;
vector <muchie> v[50005];
int main()
{
    ifstream f("bellmanford.in");
    ofstream g("bellmanford.out");
    f >> n >> m;
    for(i = 1; i <= m; i ++)
    {
        f >> x >> y >> c;
        aux.nod = y;
        aux.cost = c;
        v[x].push_back(aux);
    }
    for(i = 1; i <= n; i ++)
        d[i] = INF;
    d[1] = 0;
    aux.nod = 1;
    aux.cost = 0;
    hip.push(aux);
    while(!hip.empty())
    {
        aux = hip.top();
        hip.pop();
        if(aux.cost != d[aux.nod])continue;
        used[aux.nod]++;
        if(used[aux.nod] == n + 1)
        {
            g << "Ciclu negativ!";
            return 0;
        }
        for(i = 0; i < v[aux.nod].size(); i ++)
        {
            aux1 = v[aux.nod][i];
            if(d[aux1.nod] > d[aux.nod] + aux1.cost)
            {
                d[aux1.nod] = d[aux.nod] + aux1.cost;
                aux1.cost = d[aux1.nod];
                hip.push(aux1);
            }
        }
    }
    for(i = 2; i <= n; i ++)
        g << d[i] << " ";
    return 0;
}