Cod sursa(job #3166649)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 9 noiembrie 2023 10:35:02
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

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

#define pii pair<int, int>

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

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

void read()
{
    in>>n>>m;
    int x, y, wt;
    while (m--)
        in>>x>>y>>wt, tree[x].push_back({y, wt});
}

void dijkstra();

void solve()
{
    dijkstra();

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

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

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

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

int main()
{
    read();
    solve();
    return 0;
}