码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1182 食物链 带权并查集

时间:2015-08-01 18:46:06      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

今天一定彻底弄懂 带权并查集

 

技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <fstream>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <deque>
 7 #include <vector>
 8 #include <queue>
 9 #include <string>
10 #include <cstring>
11 #include <map>
12 #include <stack>
13 #include <set>
14 #define LL long long
15 #define INF 0x3f3f3f3f
16 //#define OPEN_FILE
17 #define MAXN 50005
18 using namespace std;
19 int n, k;
20 int father[MAXN];
21 int ranK[MAXN];
22 int find(int x){
23     if (x == father[x]) return x;
24     int y = father[x];
25     father[x] = find(father[x]);
26     ranK[x] = (ranK[x] + ranK[y]) % 3;
27     return father[x];
28 }
29 void union_set(int x, int y, int z){
30     int a = father[x], b = father[y];
31     father[a] = b;
32     ranK[a] = (z + ranK[y] - ranK[x] + 3) % 3;
33 }
34 int main()
35 {
36 #ifdef OPEN_FILE
37     freopen("in.txt", "r", stdin);
38     freopen("out.txt", "w", stdout);
39 #endif // OPEN_FILE
40     scanf("%d%d", &n, &k);
41     for (int i = 1; i <= n; i++){
42         father[i] = i;
43     }
44     memset(ranK, 0, sizeof(ranK));
45     int x, y, z;
46     int cnt = 0;
47     for (int i = 1; i <= k; i++){
48         scanf("%d%d%d", &z, &x, &y);
49         if (x > n || y > n){
50             cnt++;
51             continue;
52         }
53         if (x == y && z == 2){
54             cnt++;
55             continue;
56         }
57         int a = find(x), b = find(y);
58         if (a == b && ranK[x] != (z - 1 + ranK[y]) % 3){
59             cnt++;
60         }
61         if (a != b){
62             union_set(x, y, z - 1);
63         }
64     }
65     printf("%d\n", cnt);
66 }
View Code

 

POJ 1182 食物链 带权并查集

标签:

原文地址:http://www.cnblogs.com/macinchang/p/4694362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!