Cod sursa(job #2402973)

Utilizator PushkinPetolea Cosmin Pushkin Data 11 aprilie 2019 10:30:48
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
struct nod
{
    int x, g;
    nod(int xx, int gg)
        :x(xx), g(gg) {}
    bool operator<(nod nd)const
    {
        return (g>nd.g);
    }
};
vector<vector<nod>> G;
priority_queue<nod> h;
vector<int> res;
int n;
void rd()
{
    int x, y, g;
    f>>n>>x;
    G.resize(n+1);
    res.resize(n+1, INT_MAX);
    while(f>>x>>y>>g)
        G[x].push_back(nod(y, g));
}
void Dijkstra(int x)
{
    int g;
    h.push(nod(x, 0));
    while(h.size())
    {
        x=h.top().x;
        g=h.top().g;
        h.pop();
        if(res[x]!=INT_MAX)
            continue;
        res[x]=g;
        for(auto a:G[x])
            h.push(nod(a.x, g+a.g));
    }
}
int main()
{
    rd();
    Dijkstra(1);
    for(int i=2; i<=n; i++)
        if(res[i]!=INT_MAX)g<<res[i]<<' ';
        else g<<"0 ";
    f.close();
    g.close();
    return 0;
}