1. 程式人生 > 其它 >藍橋杯[第十屆][B組]- 完全二叉樹的權值

藍橋杯[第十屆][B組]- 完全二叉樹的權值

 

題目來自藍橋杯練習系統

這一題使用廣度優先遍歷來獲得最大和的深度

程式碼如下:

#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 範圍的滑動視窗來累加,廣度優先搜尋有些麻煩,但是作為一個重要的搜尋方法,廣度優先搜尋的思維方式和作用要更大,可以用在一些尋路問題。