[PKU3659]Cell Phone Network [USACO 2008 Jan]

很显然是树形动规(虽然网上也有贪心的做法)。因为每个节点必须被覆盖,所以设:
  • f[i][0] => i已经被其父亲覆盖
  • f[i][1] => i必须自己覆盖自己
  • f[i][2] => i将会被儿子覆盖
因此就容易得到:
  • f[i][0] = sum{min(f[son[i]][1], f[son[i]][2])}
  • f[i][1] = sum{min(f[[son[i]][1], f[son[i]][2], f[son[i]][3])}
  • f[i][2] = sum{min(f[son[i]][1], f[son[i]][2])}
  • 注意,f[i][2]中的min决策不能全为第二个(这样i就没有被孩子覆盖了),也就是说起码得保证有一个孩子是选则1的。如果没有的话,就得再枚举一遍把哪个孩子从2换到1之后f[i][2]最小。f[i][2] = min(f[i][2]-f[son[k]][2]+f[son[k]][1])
我还是喜欢写记忆化搜索,比较方便:
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)));
}

Comments