Cod sursa(job #2765969)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 30 iulie 2021 16:31:44
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>
#define NMAX 50005
#define INF 0x3f3f3f3f

using namespace std;

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

int n, m, dh, poz[NMAX];
bitset <NMAX> v;
vector <int> dist(NMAX, INF);
vector <pair <int, int>> edges[NMAX];
int heap[NMAX];

void stergeRad()
{
    heap[1] = heap[dh--];
    poz[heap[1]] = 1;

    int parent = 1;
    while(parent * 2 <= dh)
    {
        int child = parent * 2;
        if(child + 1 <= dh && dist[heap[child]] < dist[heap[child + 1]])
            child++;
        if(dist[heap[parent]] > dist[heap[child]])
        {
            swap(heap[parent], heap[child]);
            poz[heap[parent]]  = parent;
            poz[heap[child]] = child;
            parent = child;
        }
        else
            break;
    }

}

void urca(int p)
{
    int child = p, parent = child / 2;
    while(parent && dist[heap[parent]] > dist[heap[child]])
    {
        swap(heap[child], heap[parent]);
        poz[heap[child]] = child;
        poz[heap[parent]] = parent;
        child = parent;
        parent = child / 2;
    }
}

void dijkstra()
{
    while(dh)
    {
        int nod = heap[1];
        stergeRad();
        v[nod] = 1;
        for(auto child : edges[nod])
            if(dist[child.first] > dist[nod] + child.second)
            {
                bool inHeap = (dist[child.first] != INF);
                dist[child.first] = dist[nod] + child.second;
                if(inHeap)
                    urca(poz[child.first]);
                else
                {
                    dh++;
                    heap[dh] = child.first;
                    poz[child.first] = dh;
                    urca(dh);
                }
            }
    }
}

int main()
{
    f >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        f >> x >> y >> c;
        edges[x].push_back(make_pair(y, c));
        edges[y].push_back(make_pair(x, c));
    }

    heap[1] = 1;
    poz[1] = 1;
    dh = 1;
    dist[1] = 0;
    dijkstra();

    for(int i = 2; i <= n; i++)
        if(dist[i] == INF)
            g << 0 << " ";
        else g << dist[i] << " ";

    return 0;
}