Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

并查集..代码留给路人..记录每一个集合可以吃掉的集合和可以被哪个集合吃掉..

Posted by pengshihui at 2010-07-28 15:47:15 on Problem 1182
#include "stdio.h"
#include "memory.h"
int head;
int front[50001];
int next[50001];
int father[50001];
int num[50001];
void make_set(int n)
{
	for(int i=1;i<=n;++i)
	{
		father[i]=i;
		num[i]=1;
	}
	next[0]=front[0]=0;
	memset(front+1,0,sizeof(int)*n);
	memset(next+1,0,sizeof(int)*n);
}
int find_set(int x)
{
	while(x!=father[x])
		x=father[x];
	return x;
}
int Union(int x,int y)
{
	next[y]=front[y]=next[x]=front[x]=0;
	if(x==y) return x;
	if(x==0)
		return y;
	else if(y==0)
		return x;
	else
	{
		if(num[x]>num[y])
		{
			num[x]+=num[y];
			father[y]=x;
			num[y]=0;
			return x;
		}
		else
		{
			num[y]+=num[x];
			father[x]=y;
			num[x]=0;
			return y;
		}
	}
}

void Union_x(int x,int y)
{
	if(x==y) return;
	int n1=0,n2=0,n3=0,next1=next[x],next2=next[y],front1=front[x],front2=front[y];
	n1=Union(x,y);
	n2=Union(next1,next2);
	n3=Union(front1,front2);
	if(n2!=0)
	{
		next[n2]=n3;
		front[n2]=n1;
	}
	if(n3!=0)
	{
		front[n3]=n2;
		next[n3]=n1;
	}
	next[n1]=n2;
	front[n1]=n3;
}
int main(void)
{
	int a,b,c, n,k,count=0,x,y;
	scanf("%d%d",&n,&k);
	make_set(n);
	for(int i=0;i!=k;++i)
	{
		scanf("%d%d%d",&a,&b,&c);
		if(b>n||c>n) {count++;continue;}
		x=find_set(b);
		y=find_set(c);
		if(a==1)
		{
			if(front[x]==y||next[x]==y) count++;
			else Union_x(x,y);
		}
		else
		{
			if(x==y||front[x]==y) {count++;continue;}
			if(next[x]!=0) Union_x(next[x],y);
			else if(front[y]!=0) Union_x(front[y],x);
			else if(front[x]!=0&&next[y]!=0)
			{
				a=Union(front[x],next[y]);
				front[x]=next[y]=a;
				next[a]=front[y]=x;
				next[x]=front[a]=y;
			}
			else if(front[x]!=0)
			{
				front[front[x]]=y;
				next[y]=front[x];
				next[x]=y;
				front[y]=x;
			}
			else if(next[y]!=0)
			{
				front[x]=next[y];
				next[next[y]]=x;
				next[x]=y;
				front[y]=x;
			}
			else
			{
				next[x]=y;
				front[y]=x;
			}
		}
	}
	printf("%d\n",count);
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator