PAT (Advanced Level) Practice A1155 Heap Paths (30 分) (C++)(甲級)(堆、最小二叉樹)

原題鏈接

#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 1010;
int N, tag = 0;
int T[MAX];

vector<int> path;//用path存儲每條路徑
void preOrder(int root)
{
    int lChild = root*2;
    int rChild = lChild + 1;
    path.push_back(T[root]);
    if(rChild <= N)
    {
        preOrder(rChild);
        if(tag == 1 && T[root] < T[rChild]//剛開始判斷爲大/小根堆,但這裏出現了異常
           || tag == 2 && T[root] > T[rChild]) tag = 3;
    }
    if(lChild <= N)
    {
        preOrder(lChild);
        if(tag == 1 && T[root] < T[lChild]
           || tag == 2 && T[root] > T[lChild]) tag = 3;
    }
    if(lChild > N && rChild > N)//到了葉節點,打印路徑
    {
        printf("%d", path[0]);
        for(int i=1; i<path.size(); i++)
        {
            printf(" %d", path[i]);
        }
        printf("\n");
    }
    path.pop_back();
}

int main()
{
    scanf("%d", &N);
    for(int i=1; i<=N; i++) scanf("%d", &T[i]);
    if(T[1] > T[2]) tag = 1;//大根堆
    else tag = 2;//小根堆
    preOrder(1);
    if(tag == 1) printf("Max Heap\n");
    else if(tag == 2) printf("Min Heap\n");
    else if(tag == 3) printf("Not Heap\n");
	return 0;
}



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