POJ 1733 parity game (hash離散+並查集)

題目要求輸入的長度less or equal 1000000000,但是實際的問題數卻小於5000

所以我們考慮hash離散化。


解題思路如下:



我們爲每一個輸入的點,建立struct,內包含2個成員,father指向父親node,relationship表示與父節點的關係

於是我們有:

===================

圖1,我們執行的是查找操作,假設B與A是even關係,C與B是odd關係,那麼查找壓縮路徑後,可以發現A與C是odd關係,於是我們有:

C.relationship=B.relationship^C.relationship; 

對於圖2,我們執行的是合併操作,一樣可以通過假設舉例找出關係,其中xor爲輸入的B與D的關係

C.relationship=B.relationship^D.relationship^xor;

=================

#include<iostream>
using namespace std;
#define N 5005

/*
hash+離散化===================================================================================
*/
struct node
{
	int val;
	int next;
}E[N];
int v[N], cnt=0;
int hash_1(int n)
{
	int k=n%N;
	for(int e=v[k];e!=-1;e=E[e].next)
	{
		if(E[e].val==n)
			return e;
	}
	E[cnt].next=v[k];
	E[cnt].val=n;
	v[k]=cnt++;
	return cnt-1;
}
/*================================================================================================*/
/*
並查集
*/

struct num
{
	int father;
	int relationship;
}num[N];

void make_set(int n)
{
	for(int i=0;i<n;i++)
	{
		num[i].father=i;
		num[i].relationship=0;  //even
	}
}

int find_set(int x)
{
	if(x==num[x].father)
		return x;
	else
	{
		int  temp=num[x].father;
		num[x].father=find_set(num[x].father);
		num[x].relationship=num[temp].relationship^num[x].relationship; //xor
		return num[x].father;
	}
}

void union_1(int x,int y,int a,int b,int xor)
{
	num[y].father=x;
	num[y].relationship=num[a].relationship^num[b].relationship^xor;
}




void main()
{
	int xor,M1,M2,a,b,a1,b1;
	char op[7];
	int sum;
	bool flag;
	memset(v,-1,sizeof(v));
	while(cin>>M1>>M2)
	{
		flag=true;
		make_set(N);
		sum=0;
		for(int i=0;i<M2;i++)
		{
			cin>>a>>b>>op;
			a--;//半開區間(a,b],注意a--
			if(op[0]=='o')
				xor=1;
			else xor=0;
			a=hash_1(a);
			b=hash_1(b);
			a1=find_set(a);
			b1=find_set(b);
			if(a1==b1)
			{
				if(num[a].relationship^num[b].relationship!=xor)
					 flag=false;
				else
				    {if(flag)
					     sum++;
				    }
				
			}
			else
			{
			   if(flag)
			   {
				   sum++;
			   }
				union_1(a1,b1,a,b,xor);
			}
		}
		cout<<sum<<endl;
	}
	
}


發佈了35 篇原創文章 · 獲贊 42 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章