UVa 10158 - War

题目:有n个人,有四种操作:1.朋友设定;2.敌人设定;3.朋友询问;4.敌人询问。对每个操作判断合法性。

分析:并查集。通过分析可以知道,朋友都在一个集合,每个集合只能有一个敌对的集合,并且他们是相互敌对的。

(如果一个集合存在2个以上的敌人,那么他们一定是同一个集合的。)所以每个人设置一个对应的enemy,

利用sets(i+n)记录i的敌人。每次最多处理四个集合即可。

#include <iostream>
#include <cstdlib>
#include <cstdio>

using namespace std;

//union
int sets[20001];

int Find( int x )
{
	if ( x != sets[x] )
		sets[x] = Find( sets[x] );
	return sets[x];
}
//union end

int main()
{
	int n,c,x,y;
	while ( scanf("%d",&n) != EOF ) {
		for ( int i = 0 ; i < 2*n ; ++ i )
			sets[i] = i;
		while ( scanf("%d%d%d",&c,&x,&y) && c ) {
			int a1 = Find( x ),a2 = Find( x+n );
			int b1 = Find( y ),b2 = Find( y+n );
			switch( c ) {
				case 1: if ( a1 == b2 ) printf("-1\n");
						else {
							sets[a1] = b1;
							sets[a2] = b2;
						}break;
				case 2: if ( a1 == b1 ) printf("-1\n");
						else {
							sets[a1] = b2;
							sets[a2] = b1;
						}break;
				case 3: if ( a1 == b1 ) printf("1\n");
						else printf("0\n");
						break;
				case 4: if ( a1 == b2 ) printf("1\n");
						else printf("0\n");
						break;
			}	
		}
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值