Cod sursa(job #3304174)

Utilizator Alexia12345Maftei Alexia Alexia12345 Data 21 iulie 2025 14:22:04
Problema Distante Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <bits/stdc++.h>
using namespace std;

const int maxn = 50001;
const int inf = 1 << 30;
ifstream fin("distante.in");
ofstream fout("distante.out");

struct graf
{
    int nod, cost;
    graf *next;
};
int n, m,s;
bool ok;
graf *a[maxn];
int d[maxn], h[maxn], poz[maxn], k,b[maxn];

void add(int where, int what, int cost)
{
    graf *q = new graf;
    q->nod = what;
    q->cost = cost;
    q->next = a[where];
    a[where] = q;
}
void read()
{
    fin>>n>>m>>s;
    int x, y, z;
    for(int i=1;i<=n;i++)   fin>>b[i];
    for ( int i = 1; i <= m; ++i )
    {
        fin>>x>>y>>z;
        add(x, y, z);
    }
}
void swap(int x, int y)
{
    int t = h[x];
    h[x] = h[y];
    h[y] = t;
}
void upheap(int what)
{
    int tata;
    while ( what > 1 )
    {
        tata = what >> 1;
        if ( d[ h[tata] ] > d[ h[what] ] )
        {
            poz[ h[what] ] = tata;
            poz[ h[tata] ] = what;
            swap(tata, what);
            what = tata;
        }
        else	 what = 1;
    }
}
void downheap(int what)
{
    int f;
    while ( what <= k )
    {
        f = what;
        if ( (what<<1) <= k )
        {
            f = what << 1;
            if ( f + 1 <= k )
                if ( d[ h[f + 1] ] < d[ h[f] ] )
                    ++f;
        }
        else	 return;
        if ( d[ h[what] ] > d[ h[f] ] )
        {
            poz[ h[what] ] = f;
            poz[ h[f] ] = what;
            swap(what, f);
            what = f;
        }
        else	return;
    }
}
void dijkstra_heap()
{
    for ( int i = 2; i <= n; ++i )
        d[i] = inf, poz[i] = -1;
    poz[s] = 1;
    h[++k] = s;
    while (k)
    {
        int min = h[1];
        swap(1, k);
        poz[ h[s] ] = 1;
        --k;
        downheap(1);
        graf *q = a[min];
        while (q)
        {
            if ( d[q->nod] > d[min] + q->cost )
            {
                d[q->nod] = d[min] + q->cost;
                if ( poz[q->nod] != -1 )
                    upheap( poz[q->nod] );
                else
                {
                    h[++k] = q->nod;
                    poz[ h[k] ] = k;
                    upheap( k );
                }
            }
            q = q->next;
        }
    }
}

int main()
{
    int t;
    fin>>t;
    while(t--)
    {
        ok=0;
        read();
        dijkstra_heap();
        for ( int i = 2; i <= n; ++i )
        {
            if(d[i]!=b[i])  ok=1;
        }
        if(ok)  fout<<"NU"<<endl;
        else fout<<"DA"<<endl;
    }
    return 0;
}