E - 食物链

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 using namespace std;
 6 
 7 int n, k;
 8 const int maxn = 50000 + 5;
 9 int s[maxn];
10 int fa[maxn];
11 int ans = 0;
12 
13 void init(){
14     ans = 0;
15     for( int i = 0;i <= n;i++){
16         fa[i] = i;
17         s[i] = 0;   //关系
18     }
19 }
20 
21 int Find_fa(int x){
22     if(x == fa[x])
23         return x;
24     else{
25         int t = fa[x];
26         fa[x] = Find_fa(t);
27         s[x] = (s[x] + s[t])%3;
28         return fa[x];
29     }
30 }
31 
32 bool is_yes(int x, int y){
33     if(x < 1 || x > n || y < 1|| y > n)
34         return true;
35     return false;
36 }
37 
38 int main(){
39     ios::sync_with_stdio(false);
40     scanf("%d %d", &n, &k);
41     int d, x, y;
42     init();
43     while(k--){
44        scanf("%d  %d %d", &d, &x, &y);
45         if(d == 2 && x == y){
46             ans++;
47             continue;
48         }
49         if(is_yes(x, y)){
50             ans++;
51             continue;
52         }
53         int vx = Find_fa(x);
54         int vy = Find_fa(y);
55 
56         if ( vx == vy){
57             if (d == 1 && s[x] != s[y]){
58                 ans++;
59                 continue;
60             }
61             else if (d == 2 && s[x] != (s[y] + 2)%3){
62                 ans++;
63                 continue;
64             }
65         }
66         else{
67             fa[vy] = vx;
68             s[vy] = (s[x] + d - 1 + 3 - s[y])%3;
69         }
70     }
71     printf("%d\n", ans);
72     return 0;
73 }

猜你喜欢

转载自www.cnblogs.com/jaydenouyang/p/9387906.html