Cod sursa(job #326303)

Utilizator AndreiDDiaconeasa Andrei AndreiD Data 24 iunie 2009 15:55:01
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.63 kb
#include <cstdio> 
#include <cstring>

#define file_in "distante.in"
#define file_out "distante.out"

#define Inf 0x3f3f3f3f
#define MAX_N 100201

struct list
{   
        int inf,c;   
        list *urm;   
} *rel[MAX_N+1];   
int d[MAX_N+1],dh;   
int poz[MAX_N+1],h[MAX_N+1],n,m,sursa,v[MAX_N],x,y,cst;   
  
void add(int x, int y)
{
	list* q;
	q=new list;   
	q->inf=y;   
    q->c=cst;   
	q->urm=rel[x];   
	rel[x]=q;   
}

void citire()
{   
        int i;
        scanf("%d %d %d", &n,&m,&sursa);   
        dh=n;   
          
        for (i=1;i<=n;++i)
			 scanf("%d", &v[i]);
		
		for (i=1;i<=m;++i)
		{   
                scanf("%d %d %d",&x,&y,&cst);   
               /* if (x==sursa)*/
				add(x,y);
				//add(y,x);
        }   
        
		      
		for (int i=1;i<=n;++i)
		{   
                d[i]=Inf;   
                poz[i]=i;   
                h[i]=i;   
        }   
        d[sursa]=0;   
}   
  
  
void swap(int i,int j)
{   
        int aux=h[i];
		h[i]=h[j];
		h[j]=aux; 
		
        poz[h[i]]=i;   
        poz[h[j]]=j;   
}   
  
  
void heap_dw(int i)
{   
    int l=2*i,r=2*i+1,min=i;   
    if (l<=dh && d[h[l]]<d[h[min]]) min=l;   
    if (r<=dh && d[h[r]]<d[h[min]]) min=r;   
    if (min!=i)
	{   
        swap(i,min);   
        heap_dw(min);   
	}   
}   
  
  
void heap_up(int i)
{   
    int dad=i>>1;   
    if (dad)
	{   
        if (d[h[i]]<d[h[dad]])
		{
			swap(i,dad);
			heap_up(dad);
		}   
	}   
}   
  
  
int extract_min()
{   
    swap(1,dh);   
    dh--;   
    heap_dw(1);   
    return (h[dh+1]);   
}   
  
  
void dijkstra()
{   
    dh=n;   
	while (dh)
	{   
        int nmin=extract_min();   
        for (list *p=rel[nmin];p;p=p->urm)
		{   
            if (d[p->inf]>d[nmin]+p->c)
			{   
                d[p->inf]=d[nmin]+p->c;   
                heap_up(poz[p->inf]);   
			}   
        }   
	}   
	int ok=1;
    
	 ok=1;   
        for (int i=1;i<=n;++i)   
        {
			if (d[i]==Inf) d[i]=0;
			if (d[i]!=v[i])   
                  {   
                      ok=0;   
                      break;   
                  }   
		}
        if (ok==1)   
             printf("DA\n");   
             else  
             printf("NU\n");   

	
	/*for (int i=1;i<=n;++i)
		 printf("%d ", d[i]);
	printf("\n");
*/
}   
  
  
int main()
{   
	int T;
	freopen(file_in,"r",stdin);   
    freopen(file_out,"w",stdout); 
	scanf("%d", &T);
	while(T--)
	{
		memset(d,0,sizeof(d));
        citire();   
        dijkstra();
	}

	fclose(stdin);
    fclose(stdout);	
    
	return 0;   
}