P8681 [蓝桥杯 2019 省 AB] 完全二叉树的权值

做这道题的时候混淆了满二叉树和完全二叉树的概念:

满二叉树:顾名思义,就是塞满了

完全二叉树:除了最后一层之外,每一层都必须是满的,且最后一层如果不满,则所有节点都尽可能靠左。

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#define For(i, j, n) for(int i = j ; i <= n ; ++i)
using namespace std;

const int N = 1e5 + 5;

int a[N], n, st = 1, ans, maxval;

void init()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
}

int get_sum(int lv)
{
    int res = 0;
    for(int i = lv; i < min(lv * 2, n + 1); i++)
    {
        if(i > n)
        {
            puts("impossible");
            return -1;
        }
        res += a[i];
    }
    return res;
}

int main()
{
    init();
    int depth = 1;
    while(st < n)
    {
        int t = get_sum(st);
        if(t > maxval)
        {
            ans = depth;
            maxval = t;
        }
        st *= 2;depth++;
    }
    printf("%d\n", ans);
    return 0;
}

这道题也可以不用数组,每次连续读入超过2^i个节点,就重新开始计数即可。

posted @ 2024-03-04 12:17  Gold_stein  阅读(9)  评论(0编辑  收藏  举报