poj-1733 Parity game 並查集

題目鏈接


題目大意是:一個由0,1組成的數字串~~,現在你問一個人,第i位到第j位的1的個數爲奇數還是偶數。一共會告訴你幾組這樣的數

要你判斷前k組這個人回答的都是正確的,到第k+1組,這個人說的是錯的,要你輸出這個k,要是這個人回答的都是正確的,則輸出組數

odd爲奇數,even爲偶數。


w表示該點到他祖宗點的區間1的奇偶個數

數據範圍比較大 需要離散化



#include "stdio.h"
#include "map"
#include "queue"
#include "iostream"
#include "functional"
#include "math.h"
#include "algorithm"
using namespace std;
const int maxn = 100005;
const int mod = 1000000007 ;
const int inf = 1<<30;
typedef __int64 LL;
typedef pair<double,int> pii;
int n,m,cnt,flag;
int num[maxn];
map<int,int>p,w;
struct node
{
	int x,y,k;
}que[maxn];
int find( int x )
{
	if( p[x] == x ) return x;  
	int t = p[x];  
	p[x] = find( p[x] );  
	w[x] = (w[x] + w[t])%2;
	return p[x];  
}
bool merge( int a,int b,int k )
{
	int x = find( a );
	int y = find( b );
	if( x == y && w[a] != (w[b] + k)%2 )
		return true;
	else if( x < y )
	{
		p[x] = y;
		w[x] = ((( w[b] + k )%2)-w[a] + 2)%2;
	}
	else
	{
		p[y] = x;
		w[y] = (w[a] - (w[b]+k)%2 + 2)%2;
	}
	return false;
}
int main()
{
	#ifndef ONLINE_JUDGE     
	freopen("data.txt","r",stdin);     
	#endif
	char str[10];
	while( scanf("%d",&n) != EOF )
	{
		cnt = flag = 0;
		p.clear();w.clear();
		scanf("%d",&m);
		for( int i = 1; i <= m; i ++ )
		{
			scanf("%d%d%s",&que[i].x,&que[i].y,str);
			que[i].x --;
			que[i].k = str[0] == 'o'?1:0;
			num[cnt++] = que[i].x;
			num[cnt++] = que[i].y;
		}
		sort( num,num+cnt );
		cnt = unique( num,num+cnt ) - num;
		for( int i = 0; i < cnt; i ++ )
		{
			p[num[i]] = num[i];
			w[num[i]] = 0;
		}
		for( int i = 1; i <= m; i ++ )
		{
			if( !flag && merge( que[i].x,que[i].y,que[i].k ) )
				flag = i-1;
		}
		if( flag == 0 )	flag = m;
		printf("%d\n",flag);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章