Cod sursa(job #3001385)

Utilizator Razvan_GabrielRazvan Gabriel Razvan_Gabriel Data 13 martie 2023 16:21:36
Problema Distante Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.65 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int NMAX = 50001;
const int INF = 2 * 1e9 + 1;

vector <pair <int, int> > a[NMAX];
int d[NMAX], h[NMAX], poz[NMAX];

void schimb(int p1, int p2)
{
    swap(h[p1], h[p2]);
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

void urca(int h[], int p)
{
    while(p > 1 && d[h[p]] < d[h[p / 2]])
    {
        schimb(p, p / 2);
        p /= 2;
    }
}

void adauga(int h[], int &nh, int x)
{
    h[++nh] = x;
    poz[x] = nh;
    urca(h, nh);
}

void coboara(int h[], int nh, int p)
{
    while (true)
    {
        int fs = 2 * p, fd = 2 * p + 1, bun = p;
        if (fs <= nh && d[h[fs]]  < d[h[bun]])
        {
            bun = fs;
        }
        if (fd <= nh && d[h[fd]]  < d[h[bun]])
        {
            bun = fd;
        }
        if (bun == p)
        {
            break;
        }
        schimb(p, bun);
        p = bun;
    }
}

void sterge(int h[], int &nh, int p)
{
    if (p == nh)
        nh--;
    else
    {
        schimb(p, nh--);
        urca(h, p);
        coboara(h, nh, p);
    }
}

void dijkstra(int x0)
{
    d[x0] = 0;
    int nh = 0;
    adauga(h, nh, x0);
    while(nh > 0)
    {
        int x = h[1];
        sterge(h, nh, 1);
        for(auto i: a[x])
        {
            int y = i.first;
            int c = i.second;

            if(d[y] > d[x] + c)
            {
                d[y] = d[x] + c;
                if(poz[y] == 0)
                    adauga(h, nh, y);
                else
                    urca(h, poz[y]);
            }
        }
    }
}

int main()
{
    ifstream fin("distante.in");
    ofstream fout("distante.out");

    int t;
    fin >> t;

    for(int cnt = 1; cnt <= t; cnt++)
    {
        int n, m, s;
        fin >> n >> m >> s;

        vector <int> rasp_b;
        for(int i = 1; i <= n; i++)
        {
            int x;
            fin >> x;
            rasp_b.push_back(x);
        }

        for(int i = 1; i <= n; i++)
            d[i] = INF;
        for(int i = 1; i <= n; i++)
            a[i].clear();
        for(int i = 1; i <= n; i++)
            poz[i] = 0;

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

        dijkstra(s);

        bool ok = true;
        for (int i = 1; i <= n && ok; i++)
            if(d[i] != rasp_b[i - 1])
                ok = false;

        if(ok)
            fout << "DA";
        else
            fout << "NU";
        fout << "\n";
    }



    return 0;
}