【poj 1947】 Rebuilding Roads

来源:互联网 发布:siesta软件优点 编辑:程序博客网 时间:2024/05/22 05:01
分类:树形dp
题解:设dp[i][j]为以i为根的子树中分离出j个点的最小代价
树形dp解题时,一般用子树的信息来更新根,先用dfs搜索,按dfs的顺序从下向上搜索。
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int maxn = 210;int _first[maxn], _next[maxn], _to[maxn], cnt;int dp[maxn][maxn], n, p;void add(int a, int b){_next[++cnt] = _first[a];_first[a] = cnt;_to[cnt] = b;}void dfs(int now){dp[now][1] = 0;for(int i = _first[now]; i; i = _next[i]){dfs(_to[i]);for(int j = p; j >= 1; j --){int x = dp[now][j] + 1;for(int k = 0; k < j; k ++)x = min(x, dp[now][j-k]+dp[_to[i]][k]);dp[now][j] = x;}}}int main(){memset(dp, 63, sizeof dp);scanf("%d%d", &n, &p);for(int i = 1; i < n; i ++){int a, b;scanf("%d%d", &a, &b);add(a,b);}dfs(1);int min1 = dp[1][p];for(int i = 2; i <= n; i ++){min1 = min(min1, dp[i][p]+1);}printf("%d", min1);return 0;}


1 0