Codeforces Round #419 (Div. 2)-树形dp&依赖背包&-E. Karen and Supermarket

来源:互联网 发布:小米盒子破解软件 2016 编辑:程序博客网 时间:2024/05/21 22:43

http://codeforces.com/contest/816/problem/E
给定一个物品的 原价格 和现价格,问你如何买能让他在有限花费内物品最多。存在制约关系,比如买3必须买1。
树形dp。设置两种状态,一种是父节点用了打折卡。一种是父亲没有用打折卡。父亲用了二者卡,儿子不一定要用打折卡。(比方说这个打折卡就便宜了一毛钱,而加上那一毛就可以再买一个东西了)
※ 关键是 对树形背包的理解。
第一层好理解,就是01背包。这样可以保证只取一个。
为什么不能把对子节点 数量的枚举放在外面呢。
因为这个这些树的数量不是多个物品,只是一个,只能取一个。放在外面相当于是一个物品组了。其实只是一个 泛化的物品。
每一个子节点都相当于一个 泛化物品。所以要都求。

#include <bits/stdc++.h>using namespace std;/*就是在树上进行01 背包问题。  树上背包。*/const int maxn=5050;vector<int>G[maxn];int cost1[maxn];int cost2[maxn];int k,m;int dp[maxn][maxn][2];int siz[maxn];void dfs(int u,int pre){     dp[u][0][0]=0;     dp[u][1][0]=cost1[u];     dp[u][1][1]=cost2[u];     siz[u]=1;     for(int i=0;i<G[u].size();i++){         int to=G[u][i];         if(to==pre) continue;         dfs(to,u);         for(int x=siz[u];x>=0;x--){         for(int j=0;j<=siz[to];j++){             dp[u][x+j][0]=min(dp[u][x][0]+dp[to][j][0],dp[u][x+j][0]);             dp[u][x+j][1]=min(dp[u][x][1]+dp[to][j][1],dp[u][x+j][1]);             dp[u][x+j][1]=min(dp[u][x][1]+dp[to][j][0],dp[u][x+j][1]);         }         //siz[u]+=siz[to];         }         siz[u]+=siz[to];     }}int main(){   int a,b,c;    memset(dp,0x3f,sizeof(dp));    scanf("%d%d",&m,&k);    scanf("%d%d",&a,&b);    cost1[1]=a;    cost2[1]=a-b;    for(int i=2;i<=m;i++){        scanf("%d%d%d",&a,&b,&c);        //G[i].push_back(c);        G[c].push_back(i);        cost1[i]=a;        cost2[i]=a-b;    }    dfs(1,-1);    int flag;    //cout<<dp[1][4][0]<<endl;    for(int i=m;i>=0;i--){        if(dp[1][i][0]<=k||dp[1][i][1]<=k){            flag=i;break;        }    }     printf("%d\n",flag);    return 0;}
阅读全文
0 0