Cod sursa(job #3214515)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 14 martie 2024 10:25:51
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

const int max_size = 1e5 + 20, INF = 2e9 + 20;

struct str{
    int nod, cost;
    bool operator < (const str & aux) const
    {
        return cost > aux.cost;
    }
};

int d[max_size], n;
vector <pair <int, int>> mc[max_size];
priority_queue <str> pq;

void djk ()
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;
    pq.push({1, 0});
    while (!pq.empty())
    {
        int nod = pq.top().nod, val = pq.top().cost;
        pq.pop();
        if (val > d[nod])
        {
            continue;
        }
        for (auto f : mc[nod])
        {
            if (d[nod] + f.second < d[f.first])
            {
                d[f.first] = d[nod] + f.second;
                pq.push({f.first, d[f.first]});
            }
        }
    }
}

void solve ()
{
    int m;
    cin >> n >> m;
    while (m--)
    {
        int x, y, c;
        cin >> x >> y >> c;
        mc[x].push_back({y, c});
        mc[y].push_back({x, c});
    }
    djk();
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            d[i] = 0;
        }
        cout << d[i] << " ";
    }
    cout << '\n';
}

signed main ()
{
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
#endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    long long tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
    return 0;
}