Cod sursa(job #2219092)

Utilizator YouDontNeedMyNameJurcut Paul YouDontNeedMyName Data 7 iulie 2018 11:02:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
#define N_MAX 50005
#define inf 1<<30
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m,ap[N_MAX],v[N_MAX];
struct per{
    int cost;
    int vecin;
};
vector <per> lista[N_MAX];
struct compare{
    bool operator() (int d1, int d2)
    {
        return v[d1]>v[d2];
    }
};
priority_queue <int, vector<int>, compare> pq;
bool Bellman_Ford(int node)
{
    for(int i=1; i<=n; i++)
    {
        v[i]=inf;
    }
    v[node]=0;
    pq.push(node);
    while(!pq.empty())
    {
        int nod=pq.top();
        pq.pop();
        ap[nod]++;
        if(ap[nod]>=n)
        {
            return 0;
        }
        for(int i=0; i<lista[nod].size(); i++)
        {
            int vecin=lista[nod][i].vecin;
            int cost=lista[nod][i].cost;
            if(v[vecin]>v[nod]+cost)
            {
                v[vecin]=v[nod]+cost;
                pq.push(vecin);
            }
        }
    }
    return 1;
}
int main()
{
    in >> n >> m;
    for(int i=1; i<=m; i++)
    {
        per y;
        int x;
        in >> x >> y.vecin >> y.cost;
        lista[x].push_back(y);
    }
    if(Bellman_Ford(1))
    {
        for(int i=2; i<=n; i++)
            out << v[i] << ' ';
    }
    else
        out << "Ciclu negativ!";
    return 0;
}