题目大意:
唔。。是个中文题,就不用解释了哈 ~
解题思路:
其实不用纠结搞懂谁是A,谁是B,谁是C。对于每一种动物,都创建三个角色: i - A,i - B,i - C。分别用0~N,N+1~2N,2N+1~3N 表示。
然后对于比如“1 4 6”的情况,就把 4 和 6 连起来,把 4+N 和 6+N 连起来,把4+2N 和6+2N 连起来,连接之前,检查原来的关系;对于“2 4 6”的情况,把 4和6+N,4+N和6+2N,4+2N和6 连起来 ,也要检查一下以前的关系。(如果以前的关系跟现在的关系是反的,就不对,检查比如x - A和y-B或者y-C是否在同一组) 。
参考代码:
(以后还是不要用cin cout了,这里用cin cout 结果TLE,然后改了scanf ,printf就过了。。。)
1 #include <iostream> 2 #include <vector> 3 #include <map> 4 #include <string> 5 #include <queue> 6 #include <stack> 7 #include <set> 8 9 #include <cstdio> 10 #include <cstring> 11 #include <cmath> 12 #include <cstdlib> 13 using namespace std; 14 15 const int INF=0x3f3f3f3f; 16 const int SIZE=50005; 17 18 int id[SIZE*4]; 19 int n,m; 20 21 int find(int x) 22 { 23 if(x!=id[x]) id[x]=find(id[x]); 24 return id[x]; 25 } 26 void un(int p,int q) 27 { 28 p=find(p);q=find(q);id[p]=q; 29 } 30 bool same(int x,int y) 31 { 32 return find(x)==find(y); 33 } 34 35 int main() 36 { 37 int n,m; 38 int a,b,c; 39 scanf("%d%d",&n,&m); 40 for(int i=1;i<=n*3;i++) 41 id[i]=i; 42 int sum=0; 43 for(int i=0;i<m;i++) 44 { 45 scanf("%d%d%d",&a,&b,&c); 46 if(b>n||c>n) {sum++;continue;} 47 if(a==1) 48 { 49 if(same(b,c+n)||same(b,c+n*2)) 50 sum++; 51 else 52 { 53 un(b,c); 54 un(b+n,c+n); 55 un(b+n*2,c+n*2); 56 } 57 } 58 else 59 { 60 if(same(b,c)||same(b,c+2*n)) 61 sum++; 62 else 63 { 64 un(b,c+n); 65 un(b+n,c+n*2); 66 un(b+n*2,c); 67 } 68 } 69 } 70 printf("%d ",sum); 71 return 0; 72 } 73