The weight of the complete binary tree (2019 Blue Bridge Cup Zhenti)

Given a complete binary tree containing N nodes , each node in the tree has a weight, which is 1, 2, 3...N-1, N in order
from top to bottom and left to right. ,As shown below:

 

Now Xiaoming wants to add the weights of the nodes of the same depth together. He wants to know which depth has the largest sum of the weights of the nodes? If there are multiple depths with the largest sum of the weights, please output the smallest depth.

NOTE: The depth of the root is 1.

The first line of input
contains an integer N. The second row contains N integers A1, A2, . . . AN.

output
Output an integer representing the answer.

Input sample
7
1 6 5 4 3 2 1

The inside of the computer looks like this:

              1 depth is 1

   6 5 sum=11 depth is 2

4 3 2 1 sum=10 depth is 3

So the output sample is 2

Data range
For all evaluation cases, 1 ≤ N≤ 100000, −100000 ≤ Ai≤ 100000

The idea
is to use the for loop to control the cotyledon input of the same depth, the next layer is twice the previous layer, and then accumulate for comparison. Without further ado, the code above:

#include<iostream>

using namespace std;

int shu(int n)
{
	int i, j, num;
	int ans = 0, treedepth = 0, sum = 0, leaf = 1, figure = 0;

	for (i = 1; i <= n; i++) 
	{
		if (i == 1) 
			leaf = 1;
		else 
			leaf *= 2;
		sum = 0;
		for (j = 1; j <= leaf; j++)
		{
			if (figure >= n) break;
			cin >> num;
			sum += num;
			figure++;
		}
		if (ans < sum)
		{
			ans = sum;
			treedepth = i;
		}
	}
	return treedepth;
}

int main() {
	int n,deep;

	cin >> n;
	deep = shu(n);
	cout << deep << endl;

	return 0;
}

I wish you all a successful Blue Bridge Cup Provincial Championship on April 9th!
 

Guess you like

Origin blog.csdn.net/qq_64263760/article/details/123964977
Recommended