Codeforces Round #527 (Div. 3) . F Tree with Maximum Cost

题目链接
题意:给你一棵树,让你找一个顶点 i i ,使得这个点的 d i s ( i , j ) a [ j ] \sum dis(i,j)*a[j] 最大。 d i s ( i , j ) dis(i,j) i i j j 的距离。
思路:题解还是好看啊 先从1开始搜,预处理出当1为根的时候的答案记为 r e s res ,递归的过程中假设当前节点为 i i ,那么 s u m [ i ] sum[i] 数组的意义就是:从以当前顶点为根的所有子树的所有节点的权值和记为 s u m [ i ] sum[i]
预处理完成之后就是题解中神奇的re-rooting(换根)。 还是从1开始递归,假设当前根为 v v ,他的一个子节点为 t o to ,那么 v > t o v->to 就是一个换根过程,需要做一下转变,类似于莫队的转移 ,首先由于根的变化,之前v到 n o w now 的某个子节点的距离是 x + 1 x+1 的话,那么 n o w now 为根的时候这个距离就是 x x 了。 r e s res 就要减去 s u m [ k ] , s u m [ v ] sum[k],sum[v] 也要减去 s u m [ k ] sum[k] ,相应当, t o n o w to经过now 才能到的节点的到根的距离就要加1, r e s s u m [ v ] , s u m [ k ] s u m [ v ] res就要加上sum[v],sum[k]也要加上sum[v] ,然后记得回溯就行了。

#include<bits/stdc++.h>

#define LL long long
#define fi first
#define se second
#define mp make_pair
#define pb push_back

using namespace std;

LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
LL lcm(LL a,LL b){return a/gcd(a,b)*b;}
LL powmod(LL a,LL b,LL MOD){LL ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}

const int N =2e5+232;
int n,a[N];
vector<int>v[N];
LL sum[N],res,ans;
void dfs1(int now,int pre=-1,int h=0){
	LL ans=0;
	res+=1ll*h*a[now];
	sum[now]=a[now];
	for(auto k:v[now]){
		if(k==pre)continue;
		dfs1(k,now,h+1);
		sum[now]+=sum[k];
	}
}
void dfs2(int now,int p=-1){
	ans=max(ans,res);
	for(auto k:v[now]){
		if(k==p)continue;
		res-=sum[k];
		sum[now]-=sum[k];
		res+=sum[now];
		sum[k]+=sum[now];
		dfs2(k,now);
		sum[k]-=sum[now];
		res-=sum[now];
		sum[now]+=sum[k];
		res+=sum[k];
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	for(int i=1;i<n;i++){
		int s,t;
		cin>>s>>t;
		v[s].pb(t);
		v[t].pb(s);
	}
	dfs1(1);
	dfs2(1);
	cout<<ans;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40655981/article/details/88671882