Description
【2022】贝壳找房秋招测试开发工程师笔试卷2 给你一棵以T为根,有n个节点的树。(n为奇数)每个点有一个价值V,并且每个点有一个特征值P。 每个点的特征值P为:以这个点为根的子树的所有点(包括根)的价值的和。 现在牛牛想知道这n个点对应的特征值的中位数是多少,你能告诉牛牛吗?
输入格式
第一行两个正整数,分别代表T和n。n<=1e5 接下来一行共n个正整数,分别代表编号为i的点的价值V[i]。V[i]<=1e9 接下来n-1行,每行两个正整数u,v,代表u和v之间有一条边相连。
输出格式
输出一行,共一个正整数,代表n个点特征值的中位数是多少。
输入样例
2 5 1 10 100 1000 10000 1 2 3 2 3 4 5 3
输出样例
10000
提示
根据题意,2是树根,可以先画出这棵树理解题意。点1对应的特征值为1,点2对应的特征值为11111, 点3对应的特征值为11100,点4对应的特征值为1000,点5对应的特征值为10000,中位数是10000。 提示,数据范围为1e9,那么求和计算很可能超过int范围,因此数据定义时要使用long long 类型。
思路分析:看到题目要求树的结点值,使用递归
用一个结构体存储树结构
typedef std::vector<int> vector;
typedef long long ll;
struct Node {
ll p = 0;
vector vec;
}node[100005];
for (int i = 1; i < n; i++) {
std::cin >> u >> v;
node[u].vec.push_back(v);
node[v].vec.push_back(u);
}
p记录特征值,初始化为0;vector数组保存与当前点有边连接的结点
关键代码:从根结点开始向下递归,用一个is_visit数组标记以访问的结点,避免重复计算
ll dfs(int root) {
is_visit[root] = true;
for (int i = 0; i < node[root].vec.size(); i++) {
if (!is_visit[node[root].vec[i]]) {
node[root].p += dfs(node[root].vec[i]);
}
}
node[root].p += arr[root];
return node[root].p;
}
最后再对node数组进行排序,找到中间数值即可
完整代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
typedef std::vector<int> vector;
typedef long long ll;
struct Node {
ll p = 0;
vector vec;
}node[100005];
bool cmp(const Node& n1, const Node& n2) {
return n1.p < n2.p;
}
ll arr[100005];
bool is_visit[100005];
ll dfs(int root) {
is_visit[root] = true;
for (int i = 0; i < node[root].vec.size(); i++) {
if (!is_visit[node[root].vec[i]]) {
node[root].p += dfs(node[root].vec[i]);
}
}
node[root].p += arr[root];
return node[root].p;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int T, n;
std::cin >> T >> n;
for (int i = 1; i <= n; i++) {
std::cin >> arr[i];
}
int u, v;
for (int i = 1; i < n; i++) {
std::cin >> u >> v;
node[u].vec.push_back(v);
node[v].vec.push_back(u);
}
dfs(T);
std::sort(node + 1, node + 1 + n, cmp);
int t = n / 2 + 1;
printf("%lld\n", node[t].p);
return 0;
}