Cod sursa(job #2161530)

Utilizator HigherTSCIonut Manasia HigherTSC Data 11 martie 2018 19:21:07
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

const int nmax=50001;
const int inf=1<<30;

int N,M,D[nmax];
bool iq[nmax];

vector < pair <int,int> > G[nmax];

struct Compare
{
    bool operator ()(int x,int y)
    {
        return D[x]>D[y];
    }
};

priority_queue < int, vector<int>, Compare> pq;

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

void Dijkstra (int start)
{
    for (int i=1;i<=N;i++)
        D[i]=inf;
    D[start]=0;
    pq.push(start);
    iq[start]=true;
    while (!pq.empty())
    {
        int crt=pq.top();
        pq.pop();
        iq[crt]=false;
        for (unsigned int i=0;i<G[crt].size();i++)
        {
            int nb=G[crt][i].first;
            int c=G[crt][i].second;
            if(D[crt]+c<D[nb])
            {
                D[nb]=D[crt]+c;
                if (iq[nb]==false)
                {
                    pq.push(nb);
                    iq[nb]=true;
                }
            }
        }
    }
}

void Write()
{
    for (int i=2;i<=N;i++)
        if (D[i]!=inf)
            g << D[i] <<" ";
            else
                g << "0";
}

int main()
{
    Read();
    Dijkstra(1);
    Write();
    return 0;
}