PAT_甲級_1155 Heap Paths (30point(s)) (C++)【DFS/大根堆、小根堆判斷】

目錄

1,題目描述

 題目大意

2,思路

3,AC代碼

4,解題過程


1,題目描述

Sample Input 1:

8
98 72 86 60 65 12 23 50

 

Sample Output 1:

98 86 23
98 86 12
98 72 65
98 72 60 50
Max Heap

Sample Input 2:

8
8 38 25 58 52 82 70 60

 

Sample Output 2:

8 25 70
8 25 82
8 38 52
8 38 58 60
Min Heap

 

Sample Input 3:

8
10 28 15 12 34 9 8 56

 

Sample Output 3:

10 15 8
10 15 9
10 28 34
10 28 12 56
Not Heap

 題目大意

判斷一棵完全二叉樹爲大根堆、小根堆,或者不是堆。

 

2,思路

(看見完全二叉樹我就笑了)

一個DFS解決所有煩惱!

注意,我這裏用unordered_set<int> record記錄是否爲堆,以及是哪種堆:每次到達葉節點時,輸出ans序列,並判斷相鄰兩個值的大小關係,大於插入1、小於插入-1(record.insert(ans[i] > ans[i+1] ? 1 : -1))。最後判斷record的size,不等於1說明不是堆,否則根據*record.begin()判斷是哪種堆。

 

3,AC代碼

#include<bits/stdc++.h>
using namespace std;
int N, data[1005], last = -1;
vector<int>ans;
unordered_set<int> record;
void dfs(int root){
    if(root > N) return;                    // !!!出口條件
    ans.push_back(data[root]);
    if(2 * root > N && 2 * root + 1 > N){   // !!!判斷爲葉節點的條件
        for(int i = 0; i < ans.size(); i++){
            printf("%d%c", ans[i], i == ans.size()-1 ? '\n' : ' ');
            if(i < ans.size()-1)
                record.insert(ans[i] > ans[i+1] ? 1 : -1);  //記錄是否爲堆
        }
    }
    dfs(2 * root + 1);
    dfs(2 * root);
    ans.pop_back();                         // 注意出棧
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d", &N);
    for(int i = 1; i <= N; i++)
        scanf("%d", &data[i]);
    dfs(1);
    if(record.size() > 1) printf("Not Heap");
    else if(*record.begin() > 0) printf("Max Heap");
    else printf("Min Heap");
    return 0;
}

 

4,解題過程

一發入魂o(* ̄▽ ̄*)ブ

完結撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章