poj1182 食物链 **

 1 // poj1182.cpp 
2 // 与 poj-1703 Find them, Catch them 思想类似, 只是多了一种状态,rank取值为0、1、2:
3 // 0 : x 与 fa[x] 同类
4 // 1 : x 被 fa[x] 吃
5 // 2 : x 吃 fa[x]
6
7 #include "stdafx.h"
8 #include <cstdio>
9 using namespace std;
10
11 const int maxn = 50000 + 10;
12 const int maxk = 100000 + 10;
13
14 int n, k, d, x, y, ans = 0;
15 int fa[maxn], rank[maxn];
16
17 void makeSet(int tot){
18 for(int i=0; i<tot; i++){
19 fa[i] = i;
20 rank[i] = 0;
21 }
22 }
23
24 int findSet(int x){
25 if(x == fa[x])
26 return x;
27
28 int tmp = fa[x];
29 fa[x] = findSet(fa[x]);
30 rank[x] = (rank[tmp] + rank[x]) % 3;
31
32 return fa[x];
33 }
34
35 void unionSet(int x, int y, int r){
36 int fx = findSet(x);
37 int fy = findSet(y);
38 if(fx == fy) return;
39
40 int tmp = 0;
41 if(rank[x] == 1) tmp = 2;
42 else if(rank[x] == 2) tmp = 1;
43
44 rank[fx] = (rank[y] + r + tmp) % 3;
45 fa[fx] = fy;
46 }
47
48 bool isTrue(int x, int y, int r){
49 int fx = findSet(x);
50 int fy = findSet(y);
51
52 if(fx != fy) return true;
53
54 int tmp = 0;
55 if(rank[y] == 1) tmp = 2;
56 else if(rank[y] == 2) tmp = 1;
57
58 int tmp2 = (tmp + rank[x]) % 3;
59 if(tmp2 == r) return true;
60 return false;
61 }
62
63
64 int _tmain(int argc, _TCHAR* argv[])
65 {
66 scanf("%d%d", &n, &k);
67
68 //initial
69 makeSet(n);
70
71 //input
72 for(int i=0; i<k; i++){
73 scanf("%d%d%d", &d, &x, &y);
74
75 //case 3:
76 if(x > n || y > n) ans++;
77 //case 2:
78 else if(d == 2 && x == y) ans++;
79 //case 1:
80 else{
81 int r;
82 if(d == 1) r = 0;
83 else r = 2;
84
85 if(!isTrue(x, y, r)) ans++;
86 else unionSet(x, y, r);
87 }
88
89 }
90
91 printf("%d\n", ans);
92
93 return 0;
94 }
原文地址:https://www.cnblogs.com/longdouhzt/p/2348012.html