Cod sursa(job #1973191)

Utilizator isav_costinVlad Costin Andrei isav_costin Data 24 aprilie 2017 19:02:13
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.81 kb
#include <cstdio>

using namespace std;

#define inf 2<<28

struct Graf
{
    int nod, cost;

    Graf *next;
};

Graf *a[50001];

int n, m, k, s;

int d[50001], h[50001], poz[50001], prec[50001];

void add( int where, int what, int cost )
{
    Graf *q=new Graf;

    q->next=a[where];
    q->nod=what;
    q->cost=cost;

    a[where]=q;
}

void swap( int x, int y )
{
    int t;

    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( int sursa )
{
    int i;

    for( i=1;i<=n;i++ )
    {
        d[i]=inf;
        poz[i]=-1;
    }

    d[sursa]=0;
    poz[sursa]=1;

    k=1;
    h[1]=sursa;

    for( i=1;i<=n;i++ )
    {
        int min=h[1];

        swap(1,k);

        poz[h[1]]=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
                {
                    k++;

                    h[k]=q->nod;
                    poz[h[k]]=k;

                    upheap(k);
                }
            }

            q=q->next;
        }
    }
}

int main( )
{
    freopen( "distante.in", "r", stdin );
    freopen( "distante.out", "w", stdout );

    int t, x, y, c, i, same;

    scanf( "%d", &t );

    while( t )
    {
        scanf( "%d %d %d", &n, &m, &s );

        for( i=1;i<=n;i++ )
            scanf( "%d", &prec[i] );

        for( i=1;i<=m;i++ )
        {
            scanf( "%d %d %d", &x, &y, &c );

            add(x,y,c);
            add(y,x,c);
        }

        dijkstra_heap(s);

        same=1;

        for( i=1;i<=n && same;i++ )
            if( d[i]!=prec[i] )
                same=0;

        if( same )
            printf( "DA\n" );
        else
            printf( "NU\n" );

        t--;
    }

    return 0;
}