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
| #include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
const int INF(0x3F3F3F3F);
int n, ans, f[10000][3];//[0]covered from parent; [1]self cover; [2]covered from child
std::vector<int> g[10000];
int dp(const int u, const int m, const int p = INF)
{
if (f[u][m] != INF)
return f[u][m];
int sum = 0;
if (m == 0)
{
for (std::vector<int>::iterator iter = g[u].begin(); iter != g[u].end(); ++iter)
if (*iter != p)
sum += std::min(dp(*iter, 1, u), dp(*iter, 2, u));
}
else if (m == 1)
{
for (std::vector<int>::iterator iter = g[u].begin(); iter != g[u].end(); ++iter)
if (*iter != p)
sum += std::min(std::min(dp(*iter, 0, u), dp(*iter, 1, u)), dp(*iter, 2, u));
++sum;
}
else if (m == 2)
{
int delta = INF;
bool all_child(true);
for (std::vector<int>::iterator iter = g[u].begin(); iter != g[u].end(); ++iter)
if (*iter != p)
{
const int x1 = dp(*iter, 1, u), x2 = dp(*iter, 2, u);
delta = std::min(delta, x1-x2);
if (x1 <= x2)
{
sum += x1;
all_child = false;
}
else
sum += x2;
}
if (all_child)
return f[u][m] = sum+delta;
}
return f[u][m] = sum;
}
int main()
{
memset(f, 0x3F, sizeof(f));
scanf("%d", &n);
for (int i = 1, x, y; i < n; ++i)
{
scanf("%d%d", &x, &y);
g[--x].push_back(--y);
g[y].push_back(x);
}
for (int i = 1; i < n; ++i)
if (g[i].size() < 2)
f[i][0] = 0, f[i][1] = 1, f[i][2] = INF+1;
printf("%d", std::min(dp(0, 1), dp(0, 2)));
}
|