hdu 1561 The more, The Better 树形dp

来源:互联网 发布:多益网络加班怎么样 编辑:程序博客网 时间:2024/06/06 11:30

题目

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1561

题目来源:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105318#problem/H

简要题意:中文不表。

题解

建有向图,从a指向i,然后只要从0开始dfs即可。

dp[i][j]表示选定ii及子树选定共j个点的最大值。

转移起来就是像个背包一样去转移,注意这样要反向来转移。

对于每个儿子,将答案合并到自己的答案里头,枚举两边有多少点。

注意加上虚拟的0号点后总共有m+1个点。

代码

#include <iostream>#include <cstdio>#include <cmath>#include <algorithm>#include <cstring>#include <stack>#include <queue>#include <string>#include <vector>#include <set>#include <map>#define pb push_back#define mp make_pair#define all(x) (x).begin(),(x).end()#define sz(x) ((int)(x).size())#define fi first#define se secondusing namespace std;typedef long long LL;typedef vector<int> VI;typedef pair<int,int> PII;LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}// headconst int N = 205;struct Edge {    int to, nxt;    Edge(int to, int nxt) : to(to), nxt(nxt) {}    Edge() {}};int head[N];Edge e[N];void addEdge(int from, int to, int cnt) {    e[cnt] = Edge(to, head[from]);    head[from] = cnt;}void init(int n) {    for (int i = 0; i <= n; i++) head[i] = -1;}int a[N];int dp[N][N];int n, m, v;void dfs(int x) {    dp[x][1] = a[x];    for (int i = head[x]; ~i; i = e[i].nxt) {        int to = e[i].to;        dfs(to);        for (int j = m; j > 0; j--) {            for (int k = 1; k < j; k++) {                dp[x][j] = max(dp[x][j], dp[to][j-k] + dp[x][k]);            }        }    }}int main() {    while (scanf("%d%d", &n, &m) == 2 && n) {        init(n);        m++;        int ec = 0;        for (int i = 1; i <= n; i++) {            scanf("%d%d", &v, a+i);            addEdge(v, i, ec++);        }        dfs(0);        printf("%d\n", dp[0][m]);        memset(dp, 0, sizeof dp);    }    return 0;}
0 0
原创粉丝点击