Description
动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形。A吃B, B吃C,C吃A。
现有N个动物,以1-N编号。每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种。
有人用两种说法对这N个动物所构成的食物链关系进行描述:
第一种说法是"1 X Y",表示X和Y是同类。
第二种说法是"2 X Y",表示X吃Y。
此人对N个动物,用上述两种说法,一句接一句地说出K句话,这K句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。
1) 当前的话与前面的某些真的话冲突,就是假话;
2) 当前的话中X或Y比N大,就是假话;
3) 当前的话表示X吃X,就是假话。
你的任务是根据给定的N(1 <= N <= 50,000)和K句话(0 <= K <= 100,000),输出假话的总数。
Input
第一行是两个整数N和K,以一个空格分隔。
以下K行每行是三个正整数 D,X,Y,两数之间用一个空格隔开,其中D表示说法的种类。
若D=1,则表示X和Y是同类。
若D=2,则表示X吃Y。
Output
只有一个整数,表示假话的数目。
Sample Input
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
Sample Output
3
这是一个并查集,但是有几个三个集合,要注意其中的关系,我们可以设总数为num, 那么如果 x 和 y 在一个根上面,我们就说这两个是同一类的,如果 x 和 y + num 在同一个根上面,我们就说x 吃 y ,如果 x 和 y + 2 * num在一个根上面,那么我们就认为 y 吃 x,那么就可以进行判断了:
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int people, groups;
struct group
{
int fa;
int ranks;
}gro[200000];
void init( int n)///初始化函数
{
for ( int i = 0; i < n; i++ )
{
gro[i].fa = i;
gro[i].ranks = 0;
}
}
int finds( int x )///找节点的根函数
{
if (gro[x].fa == x )
return x;
else
gro[x].fa = finds(gro[x].fa);
return gro[x].fa;
}
void unite(int x, int y)///将两颗树连接起来
{
x = finds(x);
y = finds(y);
if ( x == y ) return ;
if ( gro[x].ranks < gro[y].ranks )
gro[x].fa = y;
else
{
gro[y].fa = x;
if ( gro[x].ranks == gro[y].ranks ) gro[x].ranks++;
}
}
bool same ( int x, int y )///判断两个树是否同根
{
return finds(x) == finds(y);
}
int main()
{
//freopen("in.txt","r",stdin);
int num,word;
int fir,oper,sec;
cin >> num >> word;
init(3*num+1);///初始化三倍的数组
{
int ans = 0;
while ( word > 0 )
{
word--;
scanf("%d %d %d", &oper,&fir,&sec);///用cin会超时
fir -= 1;
sec -= 1;
if ( fir >= num || sec >= num || fir < 0 || sec < 0 )
{
ans++;continue;
}
if ( oper == 1)
{
if( ame(fir,sec+num)||same(fir,sec + 2 * num ))///如果两个可以互相攻击的话就不是同一类;
{
ans++;
}
else
{
unite(fir,sec);///
unite(fir+num,sec+num);
unite(fir + 2*num,sec+2*num);///否则的话就是fir吃sec加入,
///其中包括三种情况,因为这个属于哪一组不能确定
}
}
if ( oper == 2)
{
if(same(fir,sec)||same(fir,sec+2*num))///如果连个属于同一类或者sec吃fir的话就是假话
{
ans++;
}
else
{
unite(fir,sec+num);
unite(fir+num,sec+2*num);
unite(fir+2*num,sec);///同上,如果fir可以吃sec的话就加入,注意同上有三种情况;
}
}
}
cout << ans << endl;
}
}