Cod sursa(job #418389)

Utilizator GotenAmza Catalin Goten Data 15 martie 2010 20:29:04
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.96 kb
#include<fstream.h>
int c[90100],h[90100],x[90100],y[90100],xs[20100],xd[20100],yd[20100],n,q,a[310][310],ys[20100],p[20100],hh[20100],sol[20100],
	b[310][310],comp[90100];
void qs(int i, int j)
{
	int s=i,d=j,aux,piv=h[(i+j)>>1];
	while(s<=d)
	{
		while(c[h[s]]>c[piv])
			s++;
		while(c[h[d]]<c[piv])
			d--;
		if(s<=d)
		{
			aux=h[d];
			h[d]=h[s];
			h[s]=aux;
			d--;
			s++;
		}
	}
	if(s<j)
		qs(s,j);
	if(i<d)
		qs(i,d);
}
void qsh(int i, int j)
{
	int s=i,d=j,aux,piv=hh[(i+j)>>1];
	while(s<=d)
	{
		while(p[hh[s]]>p[piv])
			s++;
		while(p[hh[d]]<p[piv])
			d--;
		if(s<=d)
		{
			aux=hh[d];
			hh[d]=hh[s];
			hh[s]=aux;
			d--;
			s++;
		}
	}
	if(s<j)
		qsh(s,j);
	if(i<d)
		qsh(i,d);
}
int com(int i)
{
	if(i!=comp[i])
		comp[i]=com(comp[i]);
	return comp[i];
}
int main()
{
	int k=0,i,j,l=1,cx,cy,t,r;
	int dx[5]={0,0,1,0,-1};
	int dy[5]={0,1,0,-1,0};
	ifstream f("matrice2.in");
	ofstream g("matrice2.out");
	f>>n>>q;
	for(i=1;i<=n;i++)
		for(j=1;j<=n;j++)
		{
			x[++k]=i;
			y[k]=j;
			f>>c[k];
			a[i][j]=k;			
			h[k]=k;
		}
	for(i=1;i<=q;i++)
		f>>xs[i]>>ys[i]>>xd[i]>>yd[i];
	qs(1,k);
	while(l<c[h[1]])
		l<<=1;
	while(l)
	{
		for(i=1;i<=q;i++)
		{
			p[i]=sol[i]+l;
			hh[i]=i;
		}
		qsh(1,q);
		for(i=1;i<=k;i++)
		{
			b[x[i]][y[i]]=0;
			comp[i]=i;
		}
		i=1;
		j=1;
		while(i<=k)
		{
			while(j<=q&&p[hh[j]]>c[h[i]])
			{
				if(com(a[xs[hh[j]]][ys[hh[j]]])==com(a[xd[hh[j]]][yd[hh[j]]]))
					sol[hh[j]]+=l;
				j++;
			}
			r=i;
			while(c[h[r]]==c[h[i]])
			{
				b[x[h[i]]][y[h[i]]]=1;
				for(t=1;t<=4;t++)
				{
					cx=x[h[i]]+dx[t];
					cy=y[h[i]]+dy[t];
					if(cx>0&&cy>0&&cx<=n&&cy<=n&&b[cx][cy])
						comp[com(a[cx][cy])]=comp[h[i]];
				}
				i++;
			}
		}
		while(j<=q)
		{
			if(com(a[xs[hh[j]]][ys[hh[j]]])==com(a[xd[hh[j]]][yd[hh[j]]]))
					sol[hh[j]]+=l;
			j++;
		}
		l>>=1;
	}
	for(i=1;i<=q;i++)
		g<<sol[i]<<'\n';
	return 0;
}