【种类并查集】P2024 [NOI2001]食物链

 1 #include
 2 using namespace std;
 3 
 4 int fa[150010];
 5 int n, k;
 6 int cnt;
 7 
 8 int find(int x)
 9 {
10     if (x == fa[x]) return x;
11     fa[x] = find(fa[x]);
12     return fa[x];
13 }
14 
15 void merge1(int a, int b)
16 {
17     fa[find(a)] = find(b);
18     fa[find(a + n)] = find(b + n);
19     fa[find(a + n * 2)] = find(b + n * 2);
20 }
21 
22 void merge2(int a, int b)
23 {
24     fa[find(a)] = find(b + n + n);
25     fa[find(a + n)] = find(b);
26     fa[find(a + n + n)] = find(b + n);
27 }
28 
29 struct Edge
30 {
31     int u, v;
32 }e[100010];
33 
34 int main()
35 {
36     cin >> n >> k;
37     for (int i = 1; i <= n * 3; i++)
38     {
39         fa[i] = i;
40     }
41     for (int i = 1; i <= k; i++)
42     {
43         int f, a, b;
44         cin >> f >> a >> b;
45         if (a > n || b > n)
46         {
47             cnt++;
48             continue;
49         }
50         if (f == 1)
51         {
52             if (find(a + n) == find(b) || find(a) == find(b + n))
53             {
54                 cnt++;
55                 continue;
56             }
57             merge1(a, b);
58         }
59         if (f == 2)
60         {
61             if (find(a) == find(b) || find(a) == find(b + n))
62             {
63                 cnt++;
64                 continue;
65             }
66             merge2(a, b);
67         }
68     }
69     cout << cnt;
70     return 0;
71 }
View Code

 

你可能感兴趣的:(【种类并查集】P2024 [NOI2001]食物链)