Cod sursa(job #489885)

Utilizator mihai995mihai995 mihai995 Data 3 octombrie 2010 22:30:00
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <fstream>
using namespace std;

struct muchie{int x,y,d;} a[1<<17];
int d[1<<16],v[1<<16],st[1<<16],heap[1<<16],poz[1<<16],n,m,s;
const int inf=1<<30;
const char raspuns[][1<<3]={"NU\n","DA\n"};

ifstream in("distante.in");
ofstream out("distante.out");

bool cmp(muchie a,muchie b)
{
    return a.x<b.x;
}

inline bool comp(int x,int y)
{
	return v[x]<v[y];
}

inline void sch(int x,int y)
{
	int d=heap[x];heap[x]=heap[y];
	heap[y]=d;d=poz[x];
	poz[x]=poz[y];poz[y]=d;
}

inline void add(int x)
{
	heap[++heap[0]]=x;
	poz[x]=heap[0];
}

inline void up(int x)
{
	if (x>1 && comp(x,x>>1))
	{
		sch(x,x>>1);
		up(x>>1);
	}
}

inline void down(int x)
{
	int m=x;
	if (2*x<=heap[0] && comp(x<<1,x))
		m=2*x;
	if (2*x<heap[0] && comp(2*x+1,x))
		m=2*x+1;
	if (m!=x)
	{
		sch(x,m);
		down(m);
	}
}

void init()
{
    for (int i=1;i<=n;i++)
	{
        v[i]=inf;
		poz[i]=-1;
	}
}

bool work()
{
    int i,j;
    sort(a+1,a+m+1,cmp);
    for (i=j=1;i<=n;i++)
    {
        for (;a[j].x<i && j<=m;j++);
        st[i]=j;
    }
    st[n+1]=m+1;
    v[s]=0;
	add(s);
	while(heap[0])
	{
		s=heap[1];
		sch(1,heap[0]--);
		poz[s]=-1;
		down(1);		
		for (i=st[s];i<st[s+1];i++)
			if (v[a[i].y]>v[s]+a[i].d)
			{
				v[a[i].y]=v[s]+a[i].d;
				if (poz[a[i].y]==-1)
					add(a[i].y);
				else
					up(poz[a[i].y]);
				if (v[a[i].y]<d[a[i].y])
					return false;
			}
	}
	for (i=1;i<=n;i++)
		if (v[i]!=d[i])
			return false;
	return true;
}

int main()
{
    int t,i;
    in>>t;
	n=(1<<16)-1;
    while (t--)
    {
        init();
        in>>n>>m>>s;
        for (i=1;i<=n;i++)
            in>>d[i];
        for (i=1;i<=m;i++)
            in>>a[i].x>>a[i].y>>a[i].d;
        out<<raspuns[work()];
    }
    return 0;
}