Cod sursa(job #504706)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 28 noiembrie 2010 15:10:37
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.93 kb
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

#define Nmax 50001

#define INF 0x3f3f3f3f

struct graf {
	int nod, cost;
	graf *next;
} *G[Nmax];

int H[Nmax], poz[Nmax], D[Nmax], cost[Nmax], N, M, L, Sursa;

void add(int where, int nod, int cost) {
	graf *p;
	p=new graf;
	p->nod=nod;
	p->cost=cost;
	p->next=G[where];
	G[where]=p;
}

void Heap_Down(int k) {
	int son=k;
	if(2*k<=L && D[H[2*k]]<D[H[son]])
		son=2*k;
	if(2*k+1<=L && D[H[2*k+1]]<D[H[son]])
		son=2*k+1;
	if(son!=k) {
		poz[H[k]]=son;
		poz[H[son]]=k;
		swap(H[k],H[son]);
		Heap_Down(son);
	}
}

void Heap_Up(int k) {
	while(k>1 && D[H[k]]<D[H[k/2]]) {
		poz[H[k]]=k/2;
		poz[H[k/2]]=k;
		swap(H[k],H[k/2]);
		k/=2;
	}
}

void insert(int val) {
	H[++L]=val;
	poz[H[L]]=L;
	Heap_Up(L);
}

void erase(int k) {
	H[k]=H[L];
	L--;
	Heap_Down(k);
}

void remove() {
	int i;
	graf *p,*q;
	for(i=1; i<=N; i++) {
		p=G[i];
		q=G[i];
		while(q) {
			q=q->next;
			p=q;
			delete p;
		}
    }
	for(i=1; i<=N; i++)    
		G[i]=NULL;
}

void dijkstra() {
	int min;
	graf *p;
	memset(D,INF,sizeof(D));
	memset(poz,-1,sizeof(poz));
	L=0;
	D[Sursa]=0; insert(Sursa);
	while(L) {
		min=H[1];
		erase(1);
		for(p=G[min]; p; p=p->next) 
			if(D[p->nod]>D[min]+p->cost) {
				D[p->nod]=D[min]+p->cost;
				if(poz[p->nod]!=-1) 
					Heap_Up(poz[p->nod]);
				else
					insert(p->nod);
			}
	}
}
	
int verif() {
	int i;
	for(i=1; i<=N; i++)
		if(D[i]!=cost[i])
			return 0;
	return 1;
}

int main() {
	freopen("distante.in","r",stdin);
	freopen("distante.out","w",stdout);
	int T, i, j, c;
	for(scanf("%d",&T); T; --T) {
		scanf("%d %d %d",&N,&M,&Sursa);
		for(i=1; i<=N; i++) 
			scanf("%d",&cost[i]);
		while(M--) {
			scanf("%d %d %d",&i,&j,&c);
			add(i,j,c);
		}
		dijkstra();
		if(verif()==1)
			printf("DA\n");
		else
			printf("NU\n");
		remove();
	}
	
	return 0;
}