B:树上子链 (dfs,树上dp)点权

传送门

题意:

给定一棵树 T ,树 T 上每个点都有一个权值。
定义一颗树的子链的大小为:这个子链上所有结点的权值和 。
请在树 T 中找出一条最大的子链并输出。

就是求树上的最长路径
dp[x]代表到x的子树中的路径的最大值

两种写法

代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#include <stack>
typedef long long ll;
#define Pll make_pair
#define PB push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int MAXN=1e5+50;
ll dp[MAXN];
int a[MAXN];
vector<int>p[MAXN];
ll ans;
void dfs(int x,int fa){
    dp[x]=a[x];
    ans=max(ans,dp[x]);
    rep(i,0,p[x].size()-1){
        int y=p[x][i];
        if(y==fa)continue;
        dfs(y,x);
        ans=max(ans,dp[y]+dp[x]);//以x为根的路径
        dp[x]=max(dp[x],dp[y]+a[x]);
    }
}
int main()
{
    ans=-1e18;
    int n;
    scanf("%d",&n);
    rep(i,1,n)scanf("%d",&a[i]);
    rep(i,1,n-1){
        int u,v;
        scanf("%d%d",&u,&v);
        p[u].PB(v);
        p[v].PB(u);
    }
    dfs(1,-1);
    printf("%lld\n",ans);
    return 0;
}

DFS比较以每个节点为根的子树中最长路径长度加上次长路径长度,取其最大值就是树的最长路径了

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#include <stack>
typedef long long ll;
#define Pll make_pair
#define PB push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int MAXN=1e5+50;
ll dp[MAXN];
int a[MAXN];
vector<int>p[MAXN];
ll ans;
void dfs(int x,int fa){
    ll d1=-1e18,d2=-1e18;//d1代表经过x的最长路径,d2代表经过x的次长路径
    dp[x]=a[x];
    ans=max(ans,dp[x]);
    rep(i,0,p[x].size()-1){
        int y=p[x][i];
        if(y==fa)continue;
        dfs(y,x);
        dp[x]=max(dp[x],dp[y]+a[x]);
        if(dp[y]>=d1)d2=d1,d1=dp[y];
        else if(dp[y]>=d2) d2=dp[y];
    }
    ans=max(ans,a[x]+max(0ll,d1)+max(0ll,d2));
}
int main()
{
    ans=-1e18;
    int n;
    scanf("%d",&n);
    rep(i,1,n)scanf("%d",&a[i]);
    rep(i,1,n-1){
        int u,v;
        scanf("%d%d",&u,&v);
        p[u].PB(v);
        p[v].PB(u);
    }
    dfs(1,-1);
    printf("%lld\n",ans);
    return 0;
}
发布了142 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44091178/article/details/104476103