首页 > 代码库 > POJ - 1182 食物链

POJ - 1182 食物链

技术分享
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 const int MAXN = 50003;
 8 
 9 int n, k, ans, d, x, y;
10 int par[MAXN], relation[MAXN];//par[x]表示x与par[x]的关系能够确定,relation[x]表示x与par[x]的关系:0表示同类,1表示par[x]吃x,2表示x吃par[x]
11 
12 int getPar(int a) {
13     if(par[a] != a) {
14         int pa = getPar(par[a]);
15         relation[a] = (relation[a] + relation[par[a]]) % 3;
16         par[a] = pa;
17     }
18     return par[a];
19 }
20 
21 void merg(int d, int a, int b) {
22     int pa = getPar(a), pb = getPar(b);
23     if(pa == pb) {
24         if((relation[b] - relation[a] + 3) % 3 != d) {
25             ++ans;
26         }
27         return ;
28     }
29     par[pb] = pa;
30     relation[pb] = (relation[x] - relation[y] + d + 3) % 3;
31 }
32 
33 int main() {
34     scanf("%d%d", &n, &k);
35     for(int i = 1; i <= n; ++i) {
36         par[i] = i;
37         relation[i] = 0;
38     }
39     ans = 0;
40     while(k-- > 0) {
41         scanf("%d%d%d", &d, &x, &y);
42         if(x > n || y > n || (d == 2 && x == y)) {
43             ++ans;
44             continue;
45         }
46         merg(d - 1, x, y);
47     }
48     printf("%d\n", ans);
49     return 0;
50 }
View Code

 

POJ - 1182 食物链