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

POJ 1182 并查集

时间:2018-04-14 23:35:59      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:ios   class   namespace   ons   bsp   return   stream   using   nbsp   

 用cin cout会超时。。。

 1 #include<iostream>
 2 #include<vector>
 3 #include<stack>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 const int maxn = 50000 + 10;
 8 int par[maxn * 3], ran[maxn * 3];
 9 int n, k;
10 
11 void init(int n)
12 {
13     for (int i = 0; i < n; i++) {
14         par[i] = i;
15         ran[i] = 0;
16     }
17 }
18 
19 int Find(int x)
20 {
21     if (par[x] == x) return x;
22     else return par[x] = Find(par[x]);
23 }
24 
25 void unite(int x, int y)
26 {
27     x = Find(x);
28     y = Find(y);
29     if (x == y) par[x] = y;
30     if (ran[x] < ran[y]) {
31         par[x] = y;
32     }
33     else {
34         par[y] = x;
35         if (ran[x] == ran[y]) ran[x]++;
36     }
37 }
38 
39 bool same(int x, int y)
40 {
41     return Find(x) == Find(y);
42 }
43 
44 int main()
45 {
46     int d, x, y, ans = 0;
47     scanf("%d%d", &n, &k);
48     init(n * 3 + 5);
49     ans = 0;
50     for (int i = 0; i < k; i++) {
51         scanf("%d%d%d", &d, &x, &y);
52         x = x - 1;
53         y = y - 1;
54         if (x < 0 || x >= n || y < 0 || y >= n) {
55             ans++;
56             continue;
57         }
58 
59         if (d == 1) {
60             if (same(x, y + n) || same(x, y + n * 2)) {
61                 ans++;
62             }
63             else {
64                 unite(x, y);
65                 unite(x + n, y + n);
66                 unite(x + n * 2, y + n * 2);
67             }
68         }
69         if (d == 2) {
70             if (same(x, y) || same(x, y + n * 2)) { //注意以下的判断
71                 ans++;
72             }
73             else {  
74                 unite(x, y + n);
75                 unite(x + n, y + n * 2);
76                 unite(x + n * 2, y);
77             }
78         }
79     }
80     printf("%d\n", ans);
81 }

 

POJ 1182 并查集

标签:ios   class   namespace   ons   bsp   return   stream   using   nbsp   

原文地址:https://www.cnblogs.com/tcctw/p/8835247.html

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