Cod sursa(job #3168518)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 12 noiembrie 2023 17:24:56
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

using ll = long long;
using pii = pair<int, int>;

const int NMAX = 1e5 + 5;
const int INF = 0x3f3f3f3f;

int n, m, cost[NMAX];
vector<vector<pii>> tree(NMAX);

void Dijkstra() {
    memset(cost, INF, sizeof cost);

    set<pii> S;
    S.insert({0, 1});
    while (!S.empty()) {
        int from, wt;
        tie(wt, from) = *S.begin();
        S.erase(S.begin());

        for (auto node : tree[from])
        {
            int to, ewt;
            tie(to, ewt) = node;
            if (wt+ewt < cost[to]) 
            {
                if (cost[to]!=INF)
                    S.erase({cost[to], to});
                cost[to] = wt+ewt;
                S.insert({cost[to], to});
            }
        }
    }
}

void read() {
    in>>n>>m;
    int x, y, wt;
    for (int i=1; i<=m; i++)
        in>>x>>y>>wt, tree[x].push_back({y, wt});
}

void solve() {
    Dijkstra();
    for (int i=2; i<=n; i++)
        out<< ((cost[i]==INF) ? 0 : cost[i])<<' ';
}

int main()
{
    read();
    solve();

    return 0;
}