樹形DP例題
DP感覺還是有點陌生,但是這個必須要強化,這類題型實在是太常見了
一、題目鏈接:hdu 1520:Anniversary party
一道比較經典的樹形DP入門題。。。。
設dp數組
dp[root][0]表示對於該節點不選
dp[root][1]表示對於該節點選
則有:
dp[root][0]+=max(dp[son][0],dp[son][1]);
dp[root][1]+=dp[son][0];
主要可分爲三個部分
一、建樹,直接用STL中vector即可
二、樹的遍歷,dfs
三、dp
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<set>
#include<vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int n;
int dp[6010][5]; //dp[root][1]表示參加宴會,dp[root][0]表示不參加宴會
int value[6010];
int father[6010];
vector<int> tree[6010];
void dfs(int root){
dp[root][0]=0;
dp[root][1]=value[root];
for(int i=0;i<tree[root].size();i++){
int son=tree[root][i];
dfs(son);
dp[root][0]+=max(dp[son][0],dp[son][1]);
dp[root][1]+=dp[son][0];
}
}
int main(){
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
scanf("%d",&value[i]);
father[i]=-1;
tree[i].clear();
}
int a,b;
while(~scanf("%d%d",&a,&b)){
if(a==0&&b==0)
break;
tree[b].push_back(a);
father[a]=b;
}
int root=1;
//找到根節點
for(int i=1;i<=n;i++){
if(father[i]==-1){
root=i;
}
}
//cout<<root<<endl;
dfs(root);
cout<<max(dp[root][1],dp[root][0])<<endl;
}
return 0;
}
二、題目鏈接:洛谷 P1040 加分二叉樹
其實感覺這題雖是一個樹形結構,但是實際上也是可以用區間DP來求解的
開始實在沒想到,就連那麼簡單的前序遍歷數的遞歸都卡了一會
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<set>
#include<vector>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
int n;
int flag; //防止最後一個數後面出現空格
ll dp[35][35]; //dp數組
int root[35][35]; //存放根節點
ll search(int l,int r){
ll now; //存放當前根節點所對應的最大加分值
if(l>r)
return 1;
if(dp[l][r]==-1){
for(int k=l;k<=r;k++){
now=search(l,k-1)*search(k+1,r)+dp[k][k];
if(now>dp[l][r]){
dp[l][r]=now;
root[l][r]=k;
}
}
}
return dp[l][r];
}
void preoder(int l,int r){
if(l>r)
return ;
if(flag==0){
flag=1;
}
else{
cout<<' ';
}
cout<<root[l][r];
preoder(l,root[l][r]-1);
preoder(root[l][r]+1,r);
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
dp[i][j]=-1;
}
}
for(int i=1;i<=n;i++){
scanf("%lld",&dp[i][i]);
root[i][i]=i;
}
ll ans=search(1,n);
printf("%lld\n",ans);
preoder(1,n);
cout<<endl;
return 0;
}