Cod sursa(job #2734581)

Utilizator Turturica_DorinTurturica Dorin Turturica_Dorin Data 1 aprilie 2021 09:00:31
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define infi (1<<30)
#define f first
#define s second
vector <pair<int, int>> heap;
vector <pair<int, int>> v[50002];
int n, m, i, x, y, dp[50002], le, z, viz[50002];

void down_heap() {
    int k = 0, min_poz = k;
    heap[0] = heap[le - 1];
    while (2 * k + 1 <= le - 1) {
        if (heap[2*k+1].s < heap[min_poz].s)
            min_poz = 2*k+1;
        else if (2*k+2 <= le-1 && heap[2*k+2].s < heap[min_poz].s) {
            min_poz = 2*k+2;
        }
        if(min_poz == k){
            break;
        }
        swap(heap[k], heap[min_poz]);
        k = min_poz;
    }
    heap.pop_back();
    le--;
}

void up_heap() {
    le++;
    int k = le - 1;
    while (k > 0 && heap[k].s < heap[k / 2].s) {
        swap(heap[k], heap[int(k / 2)]);
        k = k / 2;
    }
}

void DIJ(){
    int nc, cc;
    heap.push_back(make_pair(1,0));
    le = 1;
    while(le != 0){
        nc = heap[0].f;
        cc = heap[0].s;
        down_heap();
        if (viz[nc] == 0)
        {
            viz[nc] = 1;
            dp[nc] = cc;
            for (auto x : v[nc]) {
                if (dp[nc] + x.s < dp[x.f]) {
                    dp[x.f] = dp[nc] + x.s;
                    if( viz[x.f] == 0 ){
                        heap.push_back(make_pair(x.f, dp[nc] + x.s));
                        up_heap();
                    }
                }
            }
        }
    }
}

int main()
{
    fin>>n>>m;
    for(i = 1; i <= m; i++){
        fin>>x>>y>>z;
        v[x].push_back(make_pair(y, z));
    }
    for (i = 1; i <= n; i++)
        dp[i] = infi;
    DIJ();
    for(i = 2; i <= n; i++){
        if ( dp[i] == infi )
            fout<<0 << ' ';
        else
            fout<<dp[i]<<' ';
    }
    return 0;
}