【POJ】1182 食物链

这是《挑战设计程序竞赛》中的例题。


题目链接:http://poj.org/problem?id=1182

题意:中文题面。不赘述。

题解:

代码:

 1 //带权并查集
 2 #include<iostream>
 3 #include<cstdio>
 4 using namespace std;
 5 const int maxn = 150010;
 6 
 7 int f[maxn];
 8 int dep[maxn];//深度
 9 
10 void init(int n){
11     for(int i = 0; i <= n ;i++){
12         f[i] = i;
13         dep[i] = 1;
14     }
15 }
16 
17 int find(int x){
18     if(x == f[x])
19         return x;
20     return f[x] = find(f[x]); 
21 } 
22 
23 void join(int x,int y){
24     x = find(x);
25     y = find(y);
26     if(x == y)    return ;
27     if(dep[x] < dep[y]){
28         f[x] = y;
29     }
30     else{
31         f[y] = x;
32         if(dep[x] == dep[y])
33             dep[x]++;
34     }
35 }
36 
37 bool same(int x,int y){
38     return find(x) == find(y);
39 }
40 
41 int main(){
42     int n,k;
43     int d,x,y;
44     int ans = 0;
45     scanf("%d%d",&n,&k);
46     init(n*3);
47     for(int i = 0; i < k; i++){
48         scanf("%d%d%d",&d,&x,&y);
49         if(x <= 0 || x > n || y <= 0 || y > n || ( d == 2 && x == y)){
50             ans++;
51             continue;
52         }
53         if(d == 1){
54             //xy同类
55             if( same(x,y+n) || same(x,y+2*n)){
56                 ans++;
57                 continue;
58             }else{
59                 join(x,y);
60                 join(x+n , y+n);
61                 join(x + 2*n, y + 2*n);
62             }
63         }else{
64             //x吃y
65             if(same(x,y)||same(x,y + 2*n)){
66                 ans++;
67                 continue;
68             }else{
69                 join(x,y+n);
70                 join(x + n, y + 2*n);
71                 join(x + 2*n,y);
72             }
73         }
74     }
75     printf("%d",ans);
76     return 0;
77 }

猜你喜欢

转载自www.cnblogs.com/Asumi/p/9747727.html