Cod sursa(job #2518949)

Utilizator AndreiDeltaBalanici Andrei Daniel AndreiDelta Data 6 ianuarie 2020 19:38:54
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>
#define Dim 50001
#define Max 1e9+1
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int N,M,x,y,z,D[Dim],viz[Dim],cnt,R[Dim];

vector < pair<int,int> > V[Dim];

struct cmp
{
    bool operator () ( int x,int y)
    {
        if( D[x] > D[y] ) return 1;
            else return 0;
    }
};

priority_queue < int,vector<int>,cmp > minheap;

bool Dijkstra()
{
    D[1]=0;
    minheap.push(1);
    viz[1]=1;

    while(!minheap.empty())
    {
        int nod=minheap.top();
        minheap.pop();

        viz[nod]=0;
        R[nod]++;

        if( R[nod] == N  ) return 0;

        for(unsigned int i=0;i<V[nod].size();i++)
        {
            int vecin=V[nod][i].first;
            int cost=V[nod][i].second;

            if( D[ vecin ] > D[ nod ] + cost )
            {
                D[vecin]=D[nod]+cost;
                if( !viz[vecin] )
                {
                    viz[vecin]=1;
                    minheap.push(vecin);
                }
            }
        }
    }
    return 1;
}

int main()
{
    f>>N>>M;
    for(int i=1;i<=M;i++)
    {
        f>>x>>y>>z;
        V[x].push_back({y,z});
    }

    for(int i=1;i<=N;i++) D[i]=Max;

    if( Dijkstra() )
        for(int i=2;i<=N;i++) g<<D[i]<<" ";
    g<<"Ciclu negativ!";



    return 0;
}