题目大致可以这样表示:给出一个n个结点的树,要求选出其中的一些顶点,使得对于树中的每条边(u, v),u和v至少有一个被选中. 请给出选中顶点数最少的方案.
思路:我们可以用dp[i][0]表示在不选择节点i的情况下,以i为根节点的子树,最少需要选择的节点数;dp[i][1]表示在选择节点i的情况下,以i为根节点的子数,最少需要选择的节点数。
1.当i为叶子节点时,dp[i][0] = 0; dp[i][1] = 1;
2.当i不为叶子节点时,dp[i][0] = sum(dp[j][1]); dp[i][1] = sum(min(dp[j][0], dp[j][1])) + 1;其中j为i的子节点。
算法实现如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#define maxn 1508
using namespace std;
int childcnt[maxn], pre[maxn], dp[maxn][2], n;
void DP(int root) {
int i, d1=0, d0=0;
if (childcnt[root] == 0) {
dp[root][0] = 0;
dp[root][1] = 1;
return;
}
for (i=0; i < n; i++) {
if (pre[i] == root) {
DP(i);
d1 += min(dp[i][0], dp[i][1]);
d0 += dp[i][1];
}
}
dp[root][1] = d1 + 1;
dp[root][0] = d0;
}
int main() {
int i, dad, child, m;
while (cin >> n) {
memset(childcnt, 0, sizeof(childcnt));
memset(pre, -1, sizeof(pre));
int root = -1;
for (int i = 0; i < n; i++) {
scanf("%d:(%d)", &dad, &m);
childcnt[dad] = m;
if (root == -1) {
root = dad;
}
while (m--) {
scanf("%d", &child);
pre[child] = dad;
}
}
DP(root);
cout << min(dp[root][0], dp[root][1]) << endl;
}
return 0;
}