codeforces 1092 F. Tree with Maximum Cost(樹形dp||換根dp)

https://codeforces.com/contest/1092/problem/F
題意:
給你一棵無根樹,每個節點有個權值ai,指定一個點u,定義value=∑ai∗dist(u,i),求出value最大值

思路:換根dp,首先考慮計算以根節點爲U計算答案,首先通過一遍dfs直接求出res,然後思考一下如果變換u節點,u->to 那麼to節點子樹上dis-1,u節點其他子樹dis+1,dis-1相當於res減去to節點子樹ai的和(因爲是每個減一),所以我們在第一遍dfs計算出每個子節點子樹ai和num
換根過程:u->to
斷開連接:num[u]-=num[to]減去子樹大小 ,res-=num[to],減去子樹貢獻
連接u:num[to]+=num[u],加上u子樹大小 ,res+=num[u],把u當做子樹加上貢獻

子節點遍歷完畢,逆序還原即可

#include<bits/stdc++.h>
#include<tr1/unordered_map>
#define fi first
#define se second
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
using namespace std;
 
typedef long long ll;
typedef pair<char, ll> P;
typedef pair<P, int> LP;
const int inf = 0x3f3f3f3f;
const int N = 1e6 + 100;
const int mod = 1e9+7;
const int base=131;
tr1::unordered_map<ll,ll> mp;
inline ll mul(ll x,ll y) { return (x*y-(ll)((long double)x*y/mod)*mod+mod)%mod;}
inline ll ksm(ll a,ll b) {ll ans=1;while(b){if(b&1)ans=mul(ans,a);a=mul(a,a),b>>=1;}return ans;}
int gcd(int x, int y) {
    return y?gcd(y,x%y):x;
}
ll n,m;
ll num[N],vis[N],a[N];
ll k,ans,cnt,res;
vector<int> v[N];
 
void dfs(int x,int fa,int h)
{
	res+=h*a[x];
	num[x]+=a[x];
	for(int to:v[x])
	{
		if(to==fa) continue;
		dfs(to,x,h+1);
		num[x]+=num[to];
	}
}
void go(int x,int fa)
{
	ans=max(res,ans);
	for(int to:v[x])
	{
		if(to==fa) continue;
		res-=num[to];
		num[x]-=num[to];
		res+=num[x];
		num[to]+=num[x];
		go(to,x);
		num[to]-=num[x];
		res-=num[x];
		num[x]+=num[to];
		res+=num[to];
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
 
 
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		v[x].push_back(y);
		v[y].push_back(x);
	}
	dfs(1,-1,0);
	go(1,-1);
	cout<<ans<<endl;
 
 
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章