二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值

题目https://www.luogu.com.cn/problem/P8681

代码如下:

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
#define fs first
#define sc second
#define endl '\n'
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;

const int N = 1e5;

int minh = -1;

int n;

int sum[N],a[N];

void dfs(int node,int h){
	if(node>n)return;
	
	sum[h]+=a[node];
	
	dfs(2*node,h+1);
	dfs(2*node+1,h+1);

    if(sum[h]>sum[minh]) minh = h;
}

int main(){
	
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);

    cin>>n;
    
    for(int i=1;i<=n;i++)cin>>a[i];
    
    dfs(1,1);
    
    cout<<minh<<endl;
    
    return 0;
}

测评结果:

相关推荐
前端小L2 分钟前
贪心算法专题(十五):借位与填充的智慧——「单调递增的数字」
javascript·算法·贪心算法
前端小L10 分钟前
贪心算法专题(十四):万流归宗——「合并区间」
javascript·算法·贪心算法
1001101_QIA27 分钟前
【C++笔试题】递归判断数组是否是递增数组
开发语言·c++
hans汉斯29 分钟前
基于数据重构与阈值自适应的信用卡欺诈不平衡分类模型研究
大数据·算法·机器学习·重构·分类·数据挖掘·机器人
ZPC821031 分钟前
FANUC 机器人 PR 寄存器
人工智能·python·算法·机器人
yong999034 分钟前
超宽带系统链路 MATLAB 仿真
开发语言·算法·matlab
企鹅侠客1 小时前
第06章—实战应用篇:List命令详解与实战(上)
数据结构·windows·redis·list
历程里程碑1 小时前
LeetCode 560题:和为K子数组最优解
算法·哈希算法·散列表
qq_401700411 小时前
C/C++中的signed char和unsigned char详解
c语言·c++·算法
leoufung1 小时前
LeetCode 67. Add Binary:从面试思路到代码细节
算法·leetcode·面试