Cod sursa(job #3192688)

Utilizator VerestiucAndreiVerestiuc Andrei VerestiucAndrei Data 13 ianuarie 2024 10:18:40
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");
int n,p;
vector< vector< pair<int,int> > > adj;
int c[50005];
struct elem {
    int poz,cost;
};
bool cmp (elem a,elem b) {
    return a.cost<b.cost;
}
priority_queue<elem, vector<elem>, decltype(&cmp)> pq(cmp);
void dijkstra() {
    while (!pq.empty()) {
        auto X=pq.top();
        pq.pop();

        for (auto i : adj[X.poz])
        if (X.cost+i.second<c[i.first]) {
            c[i.first]=X.cost+i.second;
            pq.push({i.first,c[i.first]});
        }
    }
}
int main()
{
    fin>>n>>p;
    adj.resize(n+1);
    int x,y,co;
    for (int i=1; i<=p; i++){
        fin>>x>>y>>co;
        adj[x].push_back({y,co});
    }
    for (int i=1; i<=n; i++) c[i]=1e9;

    c[1]=0;
    pq.push({1,0});
    dijkstra();

    for (int i=2; i<=n; i++) {
        if (c[i]==1e9) fout<<0<<' ';
        else    fout<<c[i]<<' ';
    }
    return 0;
}