CH 5402 Course (backpack + tree packet DP)

CH 5402 Course



\(solution:\)

Very routine discussion of a question, use the tree structure shows the relationship between the different courses included (here also point to build a virtual forest into a dozen trees). Then use this concept subtree clever aftereffect eliminated because they contain the DP produced relationship. We make the necessary course before having to go to a pipe in a sub-tree full backpack, then each node to a packet backpack also meet local diffusion of the overall optimal solution to go.



\(code:\)

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>

#define ll long long
#define db double
#define rg register int

using namespace std;

int n,m,ff,top;
int a[305];
int f[305][305];

int tou[305];
struct su{
    int to,next;
}b[305];

inline int qr(){
    register char ch; register bool sign=0; rg res=0;
    while(!isdigit(ch=getchar())) if(ch=='-')sign=1;
    while(isdigit(ch)) res=res*10+(ch^48),ch=getchar();
    return sign?-res:res;
}

inline void add(int x,int y){
    b[++top].to=y; b[top].next=tou[x]; tou[x]=top;
}

inline void dfs(int i){
    for(rg j=tou[i];j;j=b[j].next){
        rg to=b[j].to; dfs(to);
        for(rg p=m;p>0;--p)
            for(rg q=0;q<p;++q)
                f[i][p]=max(f[i][p],f[i][q]+f[to][p-q]);
    }if(i)for(rg k=m;k>0;--k)f[i][k]=f[i][k-1]+a[i];
}

int main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    n=qr(); m=qr();
    for(rg i=1;i<=n;++i)
        add(qr(),i),a[i]=qr();
    dfs(0); printf("%d\n",f[0][m]);
    return 0;
}

Guess you like

Origin www.cnblogs.com/812-xiao-wen/p/11016409.html