Cod sursa(job #2834434)

Utilizator Teodor_AxinteAxinte Teodor-Ionut Teodor_Axinte Data 16 ianuarie 2022 23:06:05
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N = 100010;
const int oo = 99999999;

int n, m, viz[N], d[N];
vector<pair<int, int>> v[N];
priority_queue<pair<int, int>> q;

void Dijkstra(int source)
{
    int minn, i, k, pas, cost;
    for (int i = 1; i <= n; i++)
        if (i != source)
            d[i] = oo;
        else
            d[i] = 0;
    q.push({0, source});

    while (!q.empty())
    {
        k = q.top().second;
        q.pop();

        if (viz[k] == 0)
        {
            viz[k] = 1;
            for (auto it : v[k])
            {
                cost = it.first;
                i = it.second;
                if (d[i] > d[k] + cost)
                {
                    d[i] = d[k] + cost;
                    q.push({-d[i], i});
                }
            }
        }
    }
}

int main()
{
    int x, y, cost;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        v[x].push_back({cost, y});
    }

    Dijkstra(1);

    for (int i = 2; i <= n; i++)
        if (d[i] == oo)
            fout << "0 ";
        else
            fout << d[i] << " ";
    return 0;
}