牛客:树上子链(模拟树的直径,求最大子树)

传送门:

昨天牛客比赛,最后8分钟左右ac这道题,这题正解应该是树形dp,无奈我树形dp学的不好,最后想到树的直径,树的直径是树的特有性质,虽然我也不太确定,然后就dfs()模拟树的直径,两次dfs(),求得路程中最大权值和,没想到a了,有点小激动

模拟树的直径AC代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll maxn=1e6+5;
const ll base=131;
ll head[maxn],a[maxn];
struct node
{
    ll to,nex;
} edge[maxn<<1];
ll cnt,ans,pp;
void add(ll u,ll v)
{
    edge[cnt].to=v;
    edge[cnt].nex=head[u];
    head[u]=cnt++;
}
void dfs(ll u,ll fa,ll sum)
{
    sum+=a[u];
    if(sum<0)
    {
        sum=a[u];
    }
    if(ans<sum)
    {
        ans=sum;
        pp=u;
    }
    for(ll i=head[u]; ~i; i=edge[i].nex)
    {
          ll v=edge[i].to;
          if(v!=fa)
          {
              dfs(v,u,sum);
          }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    memset(head,-1,sizeof(head));
    ll n;
    cin>>n;
    for(ll i=1; i<=n; i++)
        cin>>a[i];
    ll u,v;
    for(ll i=1; i<n; i++)
    {
       cin>>u>>v;
        add(u,v);
        add(v,u);
    }
    ans=-199999999999999999;
    dfs(1,0,0);
    dfs(pp,0,0);
    //cout<<pp<<endl;
    cout<<ans<<endl;
}

树形dp解法:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll maxn=1e6+5;
ll dp[maxn],a[maxn],res;
vector<ll>vec[maxn];
void dfs(ll u,ll fa)
{
    dp[u]=a[u];
    ll len=vec[u].size();
    for(ll i=0;i<len;i++)
    {
        ll v=vec[u][i];
        if(v!=fa)
        {
            dfs(v,u);
            res=max(res,dp[u]+dp[v]);//两个子树连起来
            dp[u]=max(dp[u],dp[v]+a[u]);//选一个最大的子树连根
        }
    }
    res=max(res,dp[u]);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll n;
    cin>>n;
    for(ll i=1; i<=n; i++)
        cin>>a[i];
    ll u,v;
    for(ll i=1; i<n; i++)
    {
        cin>>u>>v;
        vec[u].push_back(v);
        vec[v].push_back(u);
    }
    res=-199999999999999999;
    dfs(1,0);
    cout<<res<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值