Cod sursa(job #2574922)

Utilizator 3DwArDPauliuc Edward 3DwArD Data 6 martie 2020 10:42:05
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define NMAX 50005
#define inf INT_MAX
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector< pair<int, int> > G[NMAX];
int n,m;
vector< int > cost(NMAX, inf);
bitset<NMAX> inq;
vector< int > times(NMAX);
void dijkstra(){
    queue<int> PQ;

    cost[1]=0;
    PQ.push(1);

    while(!PQ.empty()){
        int nd = PQ.front();
        inq[nd]=false;
        PQ.pop();

        for(auto it: G[nd]){
            if(cost[it.first]> cost[nd]+it.second){
                cost[it.first]=cost[nd] + it.second;

                if(!inq[it.first]){
                    if(times[it.first]>n){
                        g<<"Ciclu negativ!";
                        return;
                    }
                    PQ.push(it.first);
                    times[it.first]++;
                    inq[it.first]=true;

                }
            }
        }
    }
}

int main()
{
    f>>n>>m;

    for(int i=1,x,y,c;i<=m;i++){
        f>>x>>y>>c;
        G[x].push_back(make_pair(y,c));
    }

    dijkstra();
    for(int i=2;i<=n;i++)
        g<<cost[i]<<' ';
    return 0;
}