Cod sursa(job #2462308)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 27 septembrie 2019 08:47:27
Problema Ubuntzei Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.72 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, k, c[17], drum[2007][2007], heap[2007], a[2007];
vector <pair <int, int> > Muchii[2007];
bool viz[2007];
void DownHeap(int poz, int nod_start)
{
    if (poz * 2 > heap[0])
        return;
    if (drum[nod_start][heap[poz]] > drum[nod_start][heap[poz * 2]] || drum[nod_start][heap[poz]] > drum[nod_start][heap[poz * 2 + 1]])
    {
        if (drum[nod_start][heap[poz * 2]] <= drum[nod_start][heap[poz * 2 + 1]])
        {
            swap(a[heap[poz]], a[heap[poz * 2]]);
            swap(heap[poz], heap[poz * 2]);
            DownHeap(poz * 2, nod_start);
        }
        else
        {
            swap(a[heap[poz]], a[heap[poz * 2 + 1]]);
            swap(heap[poz], heap[poz * 2 + 1]);
            DownHeap(poz * 2 + 1, nod_start);
        }
    }
}

void UpHeap(int poz, int nod_start)
{
    if (poz / 2 < 1)
        return;
    if (drum[nod_start][heap[poz / 2]] > drum[nod_start][heap[poz]])
    {
        swap(heap[poz], heap[poz / 2]);
        swap(a[heap[poz]], a[heap[poz / 2]]);
        UpHeap(poz / 2, nod_start);
    }
}

void Adauga(int nod, int nod_start)
{
    heap[++heap[0]] = nod;
    a[nod] = heap[0];
    UpHeap(heap[0], nod_start);
}

void Sterge(int poz, int nod_start)
{
    swap(a[heap[1]], a[heap[heap[0]]]);
    swap(heap[1], heap[heap[0]]);
    heap[heap[0]] = n + 1;
    heap[0]--;
    DownHeap(poz, nod_start);
}

void Dijkstra(int x)
{
    for (int i = 1; i <= n + 1; ++i)
        drum[x][i] = (1 << 30), heap[i] = n + 1, viz[i] = false;
    drum[x][x] = 0;
    Adauga(x, x);
    viz[x] = true;
    while (heap[0] > 0)
    {
        int nod = heap[1];
        viz[nod] = false;
        Sterge(1, x);
        for (int j = 0; j < Muchii[nod].size(); ++j)
        {
            int vecin = Muchii[nod][j].first;
            int cost = Muchii[nod][j].second;
            if (drum[x][nod] + cost < drum[x][vecin])
            {
                drum[x][vecin] = drum[x][nod] + cost;
                if (viz[vecin] == true)
                {
                    UpHeap(a[vecin], x);
                }
                else
                {
                    Adauga(vecin, x);
                    viz[vecin] = true;
                }
            }
        }
    }
}

int main()
{
    fin >> n >> m >> k;
    for (int i = 1; i <= k; ++i)
        fin >> c[i];
    for (int i = 1; i <= m; ++i)
    {
        int x, y, z;
        fin >> x >> y >> z;
        Muchii[y].push_back({x, z});
        Muchii[x].push_back({y, z});
    }
    for (int i = 1; i <= n; ++i)
        Dijkstra(i);
    fin.close();
    fout.close();
    return 0;
}