TT的蘋果樹(沒有上司的舞會,樹形DP)

問題描述

在大家的三連助攻下,TT 一舉獲得了超級多的貓咪,因此決定開一間貓咖,將快樂與大家一同分享。並且在開業的那一天,爲了紀念這個日子,TT 在貓咖門口種了一棵蘋果樹。

一年後,蘋果熟了,到了該摘蘋果的日子了。

已知樹上共有 N 個節點,每個節點對應一個快樂值爲 w[i] 的蘋果,爲了可持續發展,TT 要求摘了某個蘋果後,不能摘它父節點處的蘋果。

TT 想要令快樂值總和儘可能地大,你們能幫幫他嗎?

Input

結點按 1~N 編號。

第一行爲 N (1 ≤ N ≤ 6000) ,代表結點個數。

接下來 N 行分別代表每個結點上蘋果的快樂值 w[i](-128 ≤ w[i] ≤ 127)。

接下來 N-1 行,每行兩個數 L K,代表 K 是 L 的一個父節點。

輸入有多組,以 0 0 結束。

Output

每組數據輸出一個整數,代表所選蘋果快樂值總和的最大值。

Sample input

7
1
1
1
1
1
1
1
1 3
7 4
2 3
4 5
6 4
3 5
0 0

Sample output

5

解題思路

這道題是很經典的樹形DP題目,原題爲沒有上司的舞會,對於此題,首先應該通過入度確定根節點,然後進行DP。

設dp數組爲f[i][j],其中i表示以ii爲節點的子樹能夠達到的最大氣氛值。jj取0或1,0表示不取ii節點,1表示取。那麼最終答案就是max(f[root][1],f[root][0])

狀態轉移方程也非常簡單,如果當前點取,那麼子樹必然不能取;如果當前點不取,子樹可以取也可以不取。所以狀態轉移方程如下所示,其中xxii的子樹
f[i][0]=max{f[x][1],f[x][0]}f[i][0]=\sum max\{f[x][1],f[x][0]\}
f[i][1]=ai+f[i][0]f[i][1]=a_i+\sum f[i][0]

完整代碼

//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;

const int maxn=6000+10;
struct node{
    int x,to,next;
};
node edge[maxn*2];
int n,w[maxn],head[maxn],a[maxn],l,k,cnt,_root,f[maxn][2];
void add(int x,int y){
    cnt++;
    edge[cnt].to=y;
    edge[cnt].next=head[x];
    head[x]=cnt;
}
void dp(int x){
    for (int i=head[x]; i; i=edge[i].next){
        dp(edge[i].to);
        f[x][0]+=max(f[edge[i].to][0],f[edge[i].to][1]);
        f[x][1]+=f[edge[i].to][0];
    }
    f[x][1]+=w[x];
}
int getint(){
    int x=0,s=1; char ch=' ';
    while(ch<'0' || ch>'9'){ ch=getchar(); if(ch=='-') s=-1;}
    while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar();}
    return x*s;
}
int main(){
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    cin>>n;
    for (int i=1; i<=n; i++)
        cin>>w[i];
    while(cin>>l>>k && !(l==0 && k==0)){
        add(k,l); a[l]++;
    }
    for (int i=1; i<=n; i++){
        if(a[i]==0){
            _root=i; break;
        }
    }
    dp(_root);
    cout<<max(f[_root][0],f[_root][1])<<endl;

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章