题目描述
A tree with nnn vertices is a connected undirected graph with nnn vertices and n−1n-1n−1 edges.
You are given a tree with nnn vertices. Each vertex has a value bib_ibi. Note that for any two vertices there is exactly one single path between them, whereas a simple path doesn't contain any edge more than once. The length of a simple path is considered as the number of edges in it.
You need to pick up a simple path whose length is not smaller than 111 and select a real number xxx. Let VVV be the set of vertices in the simple path. You need to calculate the maximum of ∑u∈V(−x2+bux)∣V∣\frac{\sum_{u\in V}(-x^2+b_{u}x)}{|V|}∣V∣∑u∈V(−x2+bux).
输入描述:
The first line contains a single integer nnn (2≤n≤1052\le n \le 10^52≤n≤105), indicating the number of vertices in the tree.
The second line contains nnn integers b1,b2,⋯ ,bnb_1,b_2,\cdots,b_nb1,b2,⋯,bn (−105≤bi≤105-10^5\le b_i \le 10^5−105≤bi≤105), indicating the values of each vertex.
Each line in the next n−1n-1n−1 lines contains two integers u,vu,vu,v, indicating an edge in the tree.
输出描述:
The output contains a single real number, indicating the answer.
Your answer will be accepted if and only if the absolute error between your answer and the correct answer is not greater than 10−410^{-4}10−4.
示例1
输入
2 3 2 1 2
输出
1.562500
题意: 给出一棵树,树上每点都有一个点权,求出树上的一条路径,使其点权的均值的绝对值最大。
分析: 这道题目首先需要知道求一组数上某段(段长大于1)平均值的最大值时,这段数字长度一定是2或3,因为假如这段数字包括了4个及以上的数字,都可以划分为两部分,其中一部分会得到更大的均值,比如说段长为4时,可以划分为两段,每段段长为2,这两段一定一个大于等于均值,一个小于等于均值,那此时取大于等于均值的那段就会更优。了解到这点后就可以套用到树上了,只需要枚举树上所有长度为2或3的路径,然后取一个最大值就可以了,在枚举时可以对每个点进行讨论,分两种情况,一种是该点作为一条直链中的最低点,如图:
另一种情况是该点作为一个拐点,如图:
对于第一种情况只需要在dfs过程中记录父节点和爷爷结点编号,每到一个点时更新一下最大值,而第二种情况实际上一个点会对应很多条路径,比如上面那个图就对应了三种长度为3的路径,但实际上只需要考虑点权最大的那两个子节点,这样得到的均值才是最大的。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
using namespace std;
int w[100005];
vector<int> g[100005];
bool vis[100005];
double ans;
void dfs(int now, int pre, int ppre){
vector<int> t;
for(int i = 0; i < g[now].size(); i++){
int to = g[now][i];
if(!vis[to]){
vis[to] = true;
dfs(to, now, pre);
t.push_back(w[to]);
}
}
sort(t.begin(), t.end());
if(t.size() == 1)
ans = max(ans, fabs((w[now]+t[0])/2.0));
if(t.size() >= 2){
ans = max(ans, fabs((w[now]+t[t.size()-1]+t[t.size()-2])/3.0));
ans = max(ans, fabs((w[now]+t[0]+t[1])/3.0));
}
if(pre != 0)
ans = max(ans, fabs((w[now]+w[pre])/2.0));
if(ppre != 0)
ans = max(ans, fabs((w[now]+w[pre]+w[ppre])/3.0));
}
bool cmp(int x, int y){
return w[x] > w[y];
}
signed main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i++)
scanf("%d", &w[i]);
for(int i = 1; i < n; i++){
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
vis[1] = true;
dfs(1, 0, 0);
printf("%.6f\n", ans*ans/4);
return 0;
}