题目:有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;
}