码迷,mamicode.com
首页 > 其他好文 > 详细

CF1092F Tree with Maximum Cost

时间:2019-11-12 21:54:44      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:pre   space   efi   names   lin   line   ace   clu   add   

洛咕

伪双倍经验,这题是边权,但是做法一样

题意:\(n\)个节点的树,每个节点有点权\(a_i\).定义\(dist(x,y)\)\(x\)\(y\)的边数.选取一个点\(v\),使得\(\sum_{i=1}^ndist(i,v)*a_i\)最大.

分析:选取的那个点\(v\)不就是树的根?相当于要以每个点为根求一次贡献,然后取\(max?\)那不就是换根\(dp?\)转移手玩一下就行了.

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#define ll long long
using namespace std;
inline int read(){
    int x=0,o=1;char ch=getchar();
    while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
    if(ch=='-')o=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*o;
}
const int N=2e5+5;
int n,a[N];ll ans,cost[N],f[N];
int tot,head[N],nxt[N<<1],to[N<<1];
inline void add(int a,int b){
    nxt[++tot]=head[a];head[a]=tot;to[tot]=b;
}
inline void pre_dfs(int u,int fa){
    cost[u]=a[u];
    for(int i=head[u];i;i=nxt[i]){
        int v=to[i];if(v==fa)continue;
        pre_dfs(v,u);cost[u]+=cost[v];
    }
}
inline void dfs(int u,int fa){
    for(int i=head[u];i;i=nxt[i]){
        int v=to[i];if(v==fa)continue;
        dfs(v,u);f[u]+=f[v]+cost[v];
    }
}
inline void dp(int u,int fa){
    for(int i=head[u];i;i=nxt[i]){
        int v=to[i];if(v==fa)continue;
        f[v]=f[u]-cost[v]+cost[1]-cost[v];
        ans=max(ans,f[v]);dp(v,u);
    }
}
int main(){
    n=read();for(int i=1;i<=n;++i)a[i]=read();
    for(int i=1;i<n;++i){
        int a=read(),b=read();
        add(a,b);add(b,a);
    }
    pre_dfs(1,0);dfs(1,0);ans=f[1];dp(1,0);
    printf("%lld\n",ans);
    return 0;
}

CF1092F Tree with Maximum Cost

标签:pre   space   efi   names   lin   line   ace   clu   add   

原文地址:https://www.cnblogs.com/PPXppx/p/11845449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!