Cod sursa(job #3192700)

Utilizator VerestiucAndreiVerestiuc Andrei VerestiucAndrei Data 13 ianuarie 2024 10:32:35
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>
#define NMAX 50005
#define ll long long
using namespace std;
ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");
int n,p;
vector< vector< pair<int,int> > > adj;
ll c[NMAX];
struct elem {
    int poz;
    ll cost;
};
bool cmp (elem a,elem b) {
    return a.cost>b.cost;
}

bool vis[NMAX];
priority_queue<elem, vector<elem>, decltype(&cmp)> pq(cmp);
void dijkstra() {
    while (!pq.empty()) {
        auto X=pq.top();
        pq.pop();

        if (vis[X.poz]) continue;
        vis[X.poz]=1;

        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);
    ll 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;
}