-
Notifications
You must be signed in to change notification settings - Fork 0
/
p85_food_chain.cpp
97 lines (75 loc) · 1.4 KB
/
p85_food_chain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <cstdio>
#include <iostream>
#define MAX_N 1000000
int par[MAX_N]; // parent
int rank[MAX_N]; // tree depth
// initialize with n elements
void init(int n){
for (int i = 0; i < n; i++) {
par[i] = i;
rank[i] = 0;
}
}
// find tree root
int find(int x) {
if (par[x] == x) {
return x;
} else {
return par[x] = find(par[x]);
}
}
// unite the groups where x and y belong
void unite(int x, int y){
x = find(x);
y = find(y);
if (x == y) return;
if (rank[x] < rank[y]) {
par[x] = y;
} else {
par[y] = x;
if (rank[x] == rank[y]) rank[x]++;
}
}
// judge if x and y belong to same group
bool same(int x, int y){
return find(x) == find(y);
}
int main(){
int N, K;
std::cin >> N >> K;
// printf("%d, %d\n", N, K);
// initialize groups
init(N*3);
int type, x, y;
int ans = 0;
for (int cnt=0; cnt < K; cnt++) {
scanf("%d", &type);
scanf("%d", &x);
scanf("%d", &y);
// printf("%d, %d, %d\n", type, x, y);
x = x-1; y = y-1;
if (x < 0 || x >= N || y < 0 || y >= N) {
ans++;
continue;
}
if (type == 1){
if (same(x, y + N) || same(x, y + 2 * N)) {
ans++;
} else {
unite(x, y);
unite(x + N, y + N);
unite(x + 2 * N, y + 2 * N);
}
} else {
if (same(x, y) | same(x, y + 2 * N)) {
ans++;
} else {
unite(x, y + N);
unite(x + N, y + 2 * N);
unite(x + 2 * N, y);
}
}
}
std::cout << ans << std::endl;
return 0;
}