描述:
略
#include<iostream>
using namespace std;
const int MAX = 50010 * 3;
int par[MAX],Rank[MAX];
int find(int x){
if(x == par[x])
return x;
return par[x] = find(par[x]);
}
void unite(int x,int y){
int a = find(x);
int b = find(y);
if(a == b)
return;
if(Rank[a] > Rank[b])
par[b] = a;
else{
par[a] = b;
if(Rank[a] == Rank[b])
Rank[b]++;
}
}
bool same(int x,int y){
return find(x) == find(y);
}
int main(){
int n,k,i,j,d,x,y;
scanf("%d%d",&n,&k);
for(i = 0;i < n; ++i){
par[i] = i;//i是A类
par[i + n] = i + n;//i是B类
par[i + n * 2] = i + n * 2;//i是C类
Rank[i] = 0;
Rank[i + n] = 0;
Rank[i + n * 2] = 0;
}
int cnt = 0;
for(i = 0;i < k; ++i){
scanf("%d%d%d",&d,&x,&y);
--x;
--y;
if(x >= n || y >= n){
cnt++;
continue;
}
if(d == 1){
if(same(x,y + n) || same(x,y + 2 * n)){//x吃y或者y吃x
cnt++;
continue;
}
unite(x,y);//如果i是A类则B也是A类
unite(x + n,y + n);
unite(x + n * 2,y + n * 2);
}
else{
if(x == y || same(x,y) || same(x,y + n * 2)){
cnt++;
continue;
}
unite(x,y + n);
unite(x + n,y + n * 2);
unite(x + n * 2,y);
}
}
printf("%d",cnt);
return 0;
}
并查集 按秩归并 路径压缩会了吗? 会了!
做题目 …???
同一组中是同一种情况。