Cod sursa(job #3213085)

Utilizator maiaauUngureanu Maia maiaau Data 12 martie 2024 14:30:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int,int>;
#define pb push_back

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int oo = 0x3f3f3f3f;

int n;
vector<int> cst;
vector<vector<pii>> e;

void read(), dijkstra();

int main()
{
    read();
    dijkstra();

    for (int i = 2; i <= n; i++)   
        fout << (cst[i] == oo ? 0 : cst[i]) << ' ';
   
    return 0;
}

void read(){
    int m; fin >> n >> m;
    e.resize(n+2); cst.resize(n+2, oo);
    while (m--){
        int a, b, c; fin >> a >> b >> c;
        e[a].pb({b,c});
    }
}
void dijkstra(){
    cst[1] = 0;
    set<pii> s; s.insert({0, 1});
    while (!s.empty()){
        int c, from; 
        tie(c, from) = *s.begin();
        s.erase(s.begin());
        for (auto it: e[from]){
            int to, cm; tie(to, cm) = it;
            if (c + cm < cst[to]){
                if (cst[to] != oo)
                    s.erase({cst[to], to});
                cst[to] = c + cm;
                s.insert({cst[to], to});
            }
        }
    }
}

//14:25