C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
双指针
$通过双指针模拟一下完全二叉树即可$
$\color{red}{图解:}$
$时间复杂度:O(n)$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int n;
int a[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i ++) cin >> a[i];
ll max1 = -1e18;
int depth = 0; // 记录权值最大的层数
for (int d = 1, i = 1; i <= n; i *= 2, d ++) {
ll s = 0;
for (int j = i; j < i + (1 << d - 1) && j <= n; j ++)
s += a[j];
if (s > max1) {
max1 = s;
depth = d;
}
}
cout << depth;
return 0;
}