-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathP2170.c
More file actions
61 lines (54 loc) · 1.22 KB
/
P2170.c
File metadata and controls
61 lines (54 loc) · 1.22 KB
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
#include <stdio.h>
#include <stdlib.h>
#define maxn 20000
#define maxm 20000
short uset[maxn];
short dp[maxm];
void Init(int n) {
for (int i = 0; i < n; i++)
uset[i] = -1;
}
int FindRoot(int a) {
if (uset[a] < 0) return a;
return (uset[a] = FindRoot(uset[a]));
}
void Union(int a, int b) {
int ra = FindRoot(a), rb = FindRoot(b);
if (ra == rb) return;
if (uset[ra] < uset[rb]) {
uset[ra] += uset[rb];
uset[rb] = ra;
}
else {
uset[rb] += uset[ra];
uset[ra] = rb;
}
}
int Closer(int a, int b, int target) {
int at = abs(a - target);
int bt = abs(b - target);
return at == bt ? (a < b ? a : b) : (at < bt ? a : b);
}
int main() {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
Init(n);
int a, b;
for (int i = 0; i < k; i++) {
scanf("%d %d", &a, &b);
a--; b--;
Union(a, b);
}
//DP
int i, j, tmp;
for (i = 0; i < n; i++) {
if (uset[i] >= 0) continue;
tmp = -uset[i];
for (j = m; j > tmp; j--)
dp[j] = Closer(dp[j], dp[j - tmp] + tmp, j);
for (j = tmp; j > 0; j--)
dp[j] = Closer(dp[j], tmp, j);
}
printf("%hd\n", dp[m]);
exit(0);
}