D Tokitsukaze and Energy Tree【2023牛客寒假算法基础集训营2】

D Tokitsukaze and Energy Tree

原题链接

题意

  • 给出一棵树,将树的每个节点赋值,赋值后能够获得子数总和的能量,求可能获得的总能量最多是多少?

思路

  1. 将能量最多的赋值给层数最高的(排序)

代码

点击查看代码
#include<algorithm>
#include<iostream>
using namespace std;

#define prep(i,a,b) for(int i = (a); i <= (b); i ++)
#define rrep(i,a,b) for(int i = (a); i >= (b); i --)

typedef long long LL;
int T, n, m;
const int N = 2e5 + 10;
int f[N],v[N],cnt[N];
LL res;

bool cmp(int a,int b){
	return a > b;
}

void solve() {
	cnt[1] = 1;
	cin >> n;
	prep(i,2,n){
		cin >> f[i];
		cnt[i] = cnt[f[i]] + 1; 	//维护层数
	}
	prep(i,1,n)cin >> v[i];
	sort(cnt+1,cnt+n+1,cmp);
	sort(v+1,v+n+1,cmp);
	prep(i,1,n){
		res += (LL)cnt[i] * v[i];
	}
	cout << res << nl;
}



int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
    solve();
	return 0;
}
posted @ 2023-01-18 21:09  Keith-  阅读(23)  评论(0编辑  收藏  举报