Cod sursa(job #2357524)

Utilizator Ciprian_PizzaVasile Capota Ciprian_Pizza Data 27 februarie 2019 15:14:39
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define nmax 50002
#define oo 1e9

using namespace std;

struct Graf
{
    int nod, cost;
    bool operator <(const Graf &e) const
    {
        return cost > e.cost;
    }
};

int n,m,d[nmax],viz[nmax];
vector < pair<int, int> > L[nmax];

void citire()
{
    ifstream fin("dijkstra.in");
    int x,y,c;
    fin >> n >> m;
    while(fin >> x >> y >> c)
        L[x].push_back({y,c});
    fin.close();
}

void dijkstra(int k)
{
    int j,nod;
    for(j = 1; j <= n; j++)
        d[j] = oo;
    d[k] = 0;
    priority_queue <Graf> q;
    q.push({k,0});
    while(!q.empty())
    {
        Graf top = q.top();
        q.pop();
        if(viz[top.nod] == 0)
        {
            viz[top.nod] = 1;
            for(auto i : L[top.nod])
            {
                if(d[i.first] > d[top.nod] + i.second)
                {
                    d[i.first] = d[top.nod] + i.second;
                    q.push({i.first,d[top.nod]+i.second});
                }
            }
        }
    }
    ofstream fout("dijkstra.out");
    int i;
    for(i = 2; i <= n; i++)
        if(d[i] != oo) fout << d[i] << " ";
        else fout << 0 << " ";
    fout.close();
}

int main()
{
    citire();
    dijkstra(1);
    return 0;
}