Blue Bridge Cup - 2019 C ++ A group of Question 6: complete binary tree weights [enumeration]

I, entitled

Given an N nodes comprise a complete binary tree, each node of the tree has a weight, from the press

On the lower, left to right, followed by A1, A2, · · · AN, as shown below:

Right node of the same depth value is now Xiao Ming put together, which he would like to know the depth of the node

The sum of the maximum weight? If you have more weight and depth with the maximum, minimum depth you output them.

Note: the depth of the root is 1.

[Input Format]

The first row contains an integer N.

The second line contains N integers A1, A2, 

· · · 

AN 。

[Output format]

Output An integer represents the answer.

[Sample input]

7

1 6 5 4 3 2 1

[Sample output]

2

[Evaluation] Examples scale and agreed with

For the evaluation all use cases, 1 ≤ N ≤ 100000, 100000 ≤ Ai ≤ 100000.

Second, the idea

In fact, a violent enumeration calculated for each weight and depth, and then find that the maximum weight.

This involves the complete binary nature also soled formula NUMBERS.

In nature, the depth of the complete binary tree is Iog2 (n + 1) rounded up, 2 is low, the number of the n + 1. Since library functions inside the log () is the default base number e, so the log () is actually ln.

Another important property is that complete binary tree has i-th layer 2 ^ (i-1) th node.

Therefore, we use the formula soled, log2 (n + 1) is written log (n + 1) / log2 depth to represent a binary tree.

Because it is rounded up, and uses a celi library function () in order to return the smallest integer greater than or equal to the depth value.

Third, the problem solution

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cmath>
#define INF 9999999
#define N 100005
using namespace std;
int main()
{
    int value[N]={0};//用来存储每层结点的权值
    int n;
    cin >> n ;
    for (int i=0;i<n;i++)
    {
        cin >> value[i];
    }
    int ans=1;
    int k=0;
    int max = -INF;
    for(int i=1;i<= ceil(log(n+1)/log(2));i++)//枚举每一层
    {
        int sum=0;//权值和
        for(int j=1;j<=pow(2,i-1);j++)//枚举每一层每一个结点
        {
            sum=sum+value[k++];//权值和
        }
        if(sum>max)
        {
            max=sum;//记录最大权值和。
            ans=i;//记录是第几层的。
        }
    }
    cout << ans << endl;
    return 0;
}

 

Fourth, the results

7
1 6 5 4 3 2 1
2

Process finished with exit code 0

Published 57 original articles · won praise 9 · views 3577

Guess you like

Origin blog.csdn.net/Jayphone17/article/details/104264605