代码改变世界

蓝桥杯[第十届][B组]- 完全二叉树的权值

2022-04-01 21:57  幻霞  阅读(49)  评论(0编辑  收藏  举报

 

题目来自蓝桥杯练习系统

这一题使用广度优先遍历来获得最大和的深度

代码如下:

#include <bits/stdc++.h>
#include <queue>
using namespace std;
int num[100005]= {0};
int ans=0;
int n;
// 广度优先一般使用队列 
// 图例一般是这样(索引看成节点,.是层结束符) 
// -------------------------------------------- 
//  0 . 1 2 . 3 4 5 6 . 7 8 9 10 11 12 13 14 . 
// --------------------------------------------- 
queue<int> q;
int main() {
//    取消c++对cstdio的兼容和取消输入输出流绑定 
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=0; i<n; i++) {
        cin>>num[i];
    }
//    先放入根节点和结束符 
    q.push(0);
    q.push(100005);
    
    int curSum=0;
    int maxSum=-100005;
    int depth=1;    
 
    while(!q.empty()) {
//        先取出索引 
        int idex=q.front();
        q.pop();
//        如果不为结束符就累加到当前和 
        if(idex!=100005) {
            curSum+=num[idex];
//            一般来说,完全二叉树都是在n范围内的,如果不是这样
//             可以考虑判断其内容是否为数组默认值来筛去空节点
//             如果根节点索引为0,子节点一般为i*2+1 和 i*2+2
//          如果根节点索引为1,子节点一般为i*2 和 i*2+1 可以通过输入次序来选择 
            if(idex*2<n) q.push(idex*2+1);
            if(idex*2+1<n) q.push(idex*2+2);
        }else{
//            如果当前和更大就更新结果 
            if(maxSum<curSum){
                ans=max(ans,depth);
                maxSum=curSum;
            }
            depth++;
            curSum=0;
//            如果取完队列不为空。就加一个结束符继续下一个循环,否则直接退出 
            if(!q.empty()) q.push(100005); 
        }
    }
    cout<<ans;
    return 0;
}

其实如果是完全二叉树的话可以用2^n 范围的滑动窗口来累加,广度优先搜索有些麻烦,但是作为一个重要的搜索方法,广度优先搜索的思维方式和作用要更大,可以用在一些寻路问题。