Cod sursa(job #321738)

Utilizator ilincaSorescu Ilinca ilinca Data 7 iunie 2009 02:09:50
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.89 kb
#include <stdio.h>
#include <values.h> 

#define nmax 50005
#define mmax 100005
#define tmax 15
#define cmax 1005
#define inf INT_MAX

struct ceva
{
	int nod, cost;
	ceva *next;
};

int n, m, s, size, db [nmax], d [nmax], h [nmax], p [nmax];
ceva *f [nmax];


void insert (int a, int b, int c)
{
	ceva *aux;
	aux=new ceva;
	aux->nod=b;
	aux->cost=c;
	if (f [a] == 0)
		aux->next=NULL;
	else
		aux->next=f [a];
	f [a]=aux;
}

void scan ()
{
	int a, b, c, i;
	scanf ("%d%d%d", &n, &m, &s);
	for (i=1; i <= n; ++i) 
		scanf ("%d", &db [i]);
	for (i=1; i <= m; ++i) 
	{
		scanf ("%d%d%d", &a, &b, &c);
		insert (a, b, c);
		insert (b, a, c);
	}
}


void init ()
{
	int i;
	for (i=1; i <= n; ++i) 
	{
		d [i]=inf;
		p [i]=0;
	}
}

void upheap (int k)
{
	int t=k>>1;
	if (t >= 1 && d [h [t]] > d [h [k]])
	{
		int aux=h [t];
		h [t]=h [k];
		h [k]=aux;

		p [h [k]]=k;
		p [h [t]]=t;

		upheap (t);
	}	
}

void downheap (int k)
{
	if (k << 1 > size)
	       return;
	int f=k << 1;
	
	if (f+1 <= size && d [h [f]] > d [h [f+1]]) 
		++f;
	
	if (d [h [f]] < d [h [k]]) 
	{
		int aux=h [f];
		h [f]=h [k];
		h [k]=aux;

		p [h [k]]=k;
		p [h [f]]=f;

		downheap (f);
	}	
}

void dijkstra ()
{
	size=1;
	ceva *i;
	init ();
	d [s]=0;
	h [1]=s;
	p [s]=1;

	while (size)
	{
		for (i=f [h [1]]; i != NULL ; i=i->next) 
			if (d [i->nod] > d [h [1]] + i->cost)
			{
				if (p [i->nod] == 0) 
				{
					p [i->nod]=++size;
					h [size]=i->nod;
				}
				d [i->nod]=d [h [1]] + i->cost;
				upheap (p [i->nod]);
			}	
		p [h [size]]=1;
		h [1]=h [size--];
		downheap (1);
	}	
}

bool ok ()
{
	int i;
	for (i=1; i <= n; ++i) 
		if (d [i] != db [i])
		       return false;
	return true;	
}

int main ()
{
	freopen ("distante.in", "r", stdin);
	freopen ("distante.out", "w", stdout);
	int t, i;
	scanf ("%d", &t);
	for (i=1; i <= t; ++i)
	{
		scan ();
		dijkstra ();
		if (ok ())
		       printf ("DA\n");
		else
			printf ("NU\n");	
	}	
	return 0;
}