树形dp

树形dp形式上其实是dfs,题目往往给定一个带权值的树,让你求某个属性(max,min),需要保存树的结构并深搜遍历

图的存储通常使用邻接表,用于稀疏图(邻接矩阵用于稠密图)

例题:没有上司的舞会

https://www.acwing.com/problem/content/287/

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 6010;
int happy[N];
int h[N],ne[N],e[N],idx;
int f[N][2];
int has_fa[N];
int n;
//邻接表存储图
//插入p->x的有向边
//h[p]表示p结点的head,插入均采用头插
void add(int p,int x){
    e[idx]=x,ne[idx]=h[p],h[p]=idx++;
}

void dfs(int u){
    f[u][1]=happy[u];
    for(int i=h[u];i!=-1;i=ne[i]){ //遍历子结点
        int j=e[i];
        dfs(j);
        f[u][1]+=f[j][0];
        f[u][0]+=max(f[j][0],f[j][1]);
        
    }
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++)   scanf("%d",&happy[i]);
    
    memset(h, -1, sizeof h);
    for(int i=0;i<n-1;i++){
        int a,b;
        cin>>a>>b;
        add(b,a);
        has_fa[a]=true;
    }
    int root=1;
    while(has_fa[root]) root++; //找boss
    dfs(root);
    cout<<max(f[root][0],f[root][1]);
    return 0;
}

进阶题目:蓝桥杯-生命之树;

https://www.acwing.com/problem/content/description/1222/

无向图的处理:

1.e[],ne[]大小扩容2倍

2.防止回滚,dfs增加参数father

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;

const int N = 1e5+10;
int n;
int h[N],e[2*N],ne[2*N],idx;
LL f[N];
int core[N];
bool find_fa[N];

void add(int a,int b){
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

void dfs(int u,int fa){//记录父结点防止往回走
    f[u]=core[u];
    for(int i=h[u];i!=-1;i=ne[i]){
        int j=e[i];
        if(j!=fa){
            dfs(j,u);
            f[u]+=max(f[j],0ll);
        }
    }
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++)    cin>>core[i];
    memset(h, -1, sizeof h);
    for(int i=0;i<n-1;i++){
        int a,b;
        cin>>a>>b;
        add(a, b);
        add(b, a);
        
    }
    dfs(1,-1);
    LL res=f[1];
    //for (int i = 0; i < n; i ++ )cout<<f[i]<<" ";
    for (int i = 1; i < n; i ++ ) res=max(res,f[i]);
    cout<<res;
    return 0;
    
}
posted @ 2022-02-14 16:27  秋月桐  阅读(33)  评论(0编辑  收藏  举报