代码
边输入,边处理
时间复杂度$$O(n)$$
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int main()
{
cin >> n;
ll max1 = LONG_LONG_MIN, max2 = 0;
int flag = 1, now = 1;
for (int i = 1; i <= n; i++)
{
int t;
cin >> t;
max2 += t;
if ((int)pow(2, flag) - 1 == i) //如果当前是第2^flag-1个,代表flag这是flag层的最后一个元素
{
if (max1 < max2)
{
now = flag; //记录每次最大值的层号
max1 = max2;
}
flag++;
max2 = 0;
}
}
if (max2 > max1) //最后来一次特判,因为题目给的数据并没有覆盖到整个完全二叉树
{
now = flag;
}
cout << now;
return 0;
}
刚开始用的BFS,很遗憾,超时
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int a[N];
int visited[N];
int father[N];
int n;
ll sum[N];
void bfs()
{
queue<int> q;
q.push(0);
visited[0] = 1;
int head = 0, tail;
int cnt = 0;
while (!q.empty())
{
int now = q.front();
sum[cnt] += a[now];
q.pop();
for (int i = 0; i < n; i++)
{
if (!visited[i] && father[i] == now + 1)
{
q.push(i);
visited[i] = 1;
tail = i;
}
}
if (head == now)
{
cnt++;
head = tail;
}
}
}
int main()
{
cin >> n;
int cnt = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
father[i] = cnt;
if ((i + 1) % 2 == 1)
cnt++;
}
father[0] = -1;
bfs();
int max = 0;
for (int i = 0; i < cnt; i++)
if (sum[max] < sum[i])
max = i;
cout << max + 1;
return 0;
}