NC237189. Spring Tree
描述
输入描述
The first line contains an integer .
The second line contains integers - the initial state of weight.
Each of the next lines contains 2 integers - an edge between .
It's guaranteed that the given graph is a tree.
输出描述
Output an integer. maximum of maximum depth of the tree.
示例1
输入:
4 1 2 3 4 1 2 2 3 3 4
输出:
23
说明:
In the test case, keep original arrangement is a good idea.C++ 解法, 执行用时: 32ms, 内存消耗: 3960K, 提交时间: 2022-06-04 14:08:53
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=100007; int n; ll sum[N]; ll w[N]; vector<int>G[N]; ll dp[N]; ll ans=0; int sz[N]; void dfs(int x,int fa) { sz[x]=1; for(auto i:G[x]) { if(i==fa)continue; dfs(i,x); sz[x]+=sz[i]; dp[x]=max(dp[x],dp[i]); } dp[x]+=sum[n]-sum[n-sz[x]]+1; if(x!=1)ans=max(ans,dp[x]); } int main() { cin>>n; for(int i=1;i<=n;i++)cin>>w[i]; for(int i=1;i<n;i++) { int u,v; cin>>u>>v; G[u].push_back(v); G[v].push_back(u); } sort(w+1,w+1+n); for(int i=1;i<=n;i++)sum[i]=sum[i-1]+w[i]; dfs(1,1); cout<<ans; }