二叉树算法题—— [蓝桥杯 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;
}

测评结果:

相关推荐
搞全栈小苏2 小时前
基于Qt QML和C++的MQTT测试客户端(CMakeLists实现)
xml·c++·qt
啊?啊?2 小时前
18 从对象内存到函数调用:C++ 虚函数表原理(继承覆盖 / 动态绑定)+ 多态实战
开发语言·c++·多态原理
bkspiderx2 小时前
C++标准库:文件流类
开发语言·c++
一拳一个呆瓜3 小时前
【MFC】对话框属性:X Pos(X位置),Y Pos(Y位置)
c++·mfc
一拳一个呆瓜3 小时前
【MFC】对话框属性:Center(居中)
c++·mfc
AI 嗯啦3 小时前
数据结构深度解析:二叉树的基本原理
数据结构·算法
hai_qin3 小时前
十三,数据结构-树
数据结构·c++
和光同尘@4 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_024 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode