Cod sursa(job #505066)

Utilizator cdascaluDascalu Cristian cdascalu Data 30 noiembrie 2010 15:58:28
Problema Distante Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.43 kb
#include<stdio.h>
#define MAX 50001
#define INF 0x3f3f3f
int t,n,m,X,order[MAX],verif[MAX],d[MAX],nrelem;
FILE*f = fopen("distante.in","r");
FILE*g = fopen("distante.out","w");
struct H
{
	int val,order;
}heap[MAX],aux;
struct graf
{
	int nod,cost;
	graf*next;
}*a[MAX];
void add(int x,int y,int c)
{
	graf*q = new graf;
	q->nod = y;
	q->cost = c;
	q->next = a[x];
	a[x] = q;
}
int left_son(int x){return x*2;}
int right_son(int x){return x*2+1;}
int father(int x){return x/2;}
void swap(int x,int y)
{
	order[heap[x].order] = y;
	order[heap[y].order] = x;
	
	aux = heap[y];
	heap[y] = heap[x];
	heap[x] = aux;
}
void sift(int x)
{
	int son = 0;
	if(left_son(x) <= nrelem)
	{
		son = left_son(x);
		if(right_son(x) <= nrelem && heap[son].val > heap[right_son(x)].val)
			son = right_son(x);
	
		if(heap[son].val >= heap[x].val)
			son = 0;
	}		
	if(son)
	{
		swap(x,son);
		sift(son);
	}
}
void percolate(int x)
{
	if(father(x) && heap[father(x)].val > heap[x].val)
	{
		swap(x,father(x));
		percolate(father(x));
	}
}
void cut(int x)
{
	heap[x] = heap[nrelem--];
	order[heap[x].order] = x;
	sift(x);
	if(father(x) && heap[father(x)].val > heap[x].val)
		percolate(x);
}
void update(int x,int val)
{
	heap[x].val = val;
	sift(x);
	if(father(x) && heap[father(x)].val > heap[x].val)
		percolate(x);
}
void load()
{
	fscanf(f,"%d%d%d",&n,&m,&X);
	int i,A,B,C;
	nrelem = n;
	for(i=1;i<=n;++i)
	{
		fscanf(f,"%d",&verif[i]);
		order[i] = i;
		heap[i].val = INF;
		heap[i].order = i;
		d[i] = INF;
		a[i] = 0;
	}
	d[X] = 0;
	cut(X);
	for(i=1;i<=m;++i)
	{
		fscanf(f,"%d%d%d",&A,&B,&C);
		add(A,B,C);
		add(B,A,C);
		if(A == X)
		{
			d[B] = C;
			update(order[B],C);
		}
		if(B == X)
		{
			d[A] = C;
			update(order[A],C);
		}		
	}	
}
void make(int min)
{
	graf *q = 0;
	if(a[min])
		q = a[min];
	while(q)
	{
		if(d[q->nod] > d[min] + q->cost)
		{
			d[q->nod] = d[min] + q->cost;
			update(order[q->nod], d[min] + q->cost);
		}
		q = q->next;
	}
}
int main()
{
	fscanf(f,"%d",&t);
	int nr,i;
	while(t--)
	{
		load();		
		nr = 1;
		while(nr<=n)
		{
			if(heap[1].val == INF)
			{
				nr = n+1;
				continue;
			}			
			else { i = heap[1].order;cut(1);}
			
			make(i);
			++nr;
		}
		nr = 1;
		for(i=1;i<=n && nr;++i)
			if(d[i]!=verif[i])nr = 0;
		if(nr)fprintf(g,"DA\n");
		else fprintf(g,"NU\n");
	}
	fclose(f);
	fclose(g);
	return 0;
}