1. 程式人生 > 實用技巧 >PTA 關於堆的判斷題解

PTA 關於堆的判斷題解

基礎實驗4-2.5關於堆的判斷(25分)

將一系列給定數字順序插入一個初始為空的小頂堆H[]。隨後判斷一系列相關命題是否為真。命題分下列幾種:

  • x is the rootx是根結點;
  • x and y are siblingsxy是兄弟結點;
  • x is the parent of yxy的父結點;
  • x is a child of yxy的一個子結點。

輸入格式:

每組測試第1行包含2個正整數N≤1000)和M≤20),分別是插入元素的個數、以及需要判斷的命題數。下一行給出區間[內的N個要被插入一個初始為空的小頂堆的整數。之後M行,每行給出一個命題。題目保證命題中的結點鍵值都是存在的。

輸出格式:

對輸入的每個命題,如果其為真,則在一行中輸出T,否則輸出F

輸入樣例:

5 4
46 23 26 24 10
24 is the root
26 and 23 are siblings
46 is the parent of 23
23 is a child of 10

輸出樣例:

F
T
F
T


題意分析,該題意在建立一個最小堆,讓你判斷堆中資料之間的關係。
小頂堆概念:見百度
小頂堆陣列建立辦法:
void build(int x[], int n){
        //x[]為按順序輸入建立的滿二叉樹,未排序,n為元素個數
    for (int i = 1; i < n; i++) {
        
int t = i; while (t != 0 && dataa[(t - 1) / 2] > x[t]) { swap(x[t], dataa[(t - 1) / 2]);//若左右節點值小於根節點值,對其進行交換。 t = (t - 1) / 2; //讓小值節點上冒,再將指標指到交換後的根節點,一直判斷交換,直到到樹根為止 } } //該函式用陣列模擬堆。 //陣列堆的特性:陣列中的資料對應每一個節點。 //該節點的(下標值-1)/2即為其根節點的陣列下標值 }

完整程式碼:註釋的比較清楚,易於理解,通過草稿紙演算一遍就能看明白

/*XAN不會coding
PT關於堆的判斷 2020.12.03*/
#include<iostream>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<string>
#include<map>
#include <algorithm>
#define swap(a,b) {a=a^b;b=a^b;a=a^b;}
using namespace std;
int dataa[1005];
map<int, int>mp;
void build(int x[], int n){
    for (int i = 1; i < n; i++) {
        int t = i;
        while (t != 0 && dataa[(t - 1) / 2] > x[t]) {
            swap(x[t], dataa[(t - 1) / 2]);//若左右節點值小於根節點值,對其進行交換。
            t = (t - 1) / 2;
            //讓小值節點上冒,再將指標指到交換後的根節點,一直判斷交換,直到到樹根為止
        }
    }
    //該函式用陣列模擬堆。
    //陣列堆的特性:陣列中的資料對應每一個節點。
    //該節點的(下標值-1)/2即為其根節點的陣列下標值
}
int main() {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> dataa[i];
    }
    getchar();//常規操作,消去換行字元
    build(dataa, n);
    //以下是本題關鍵,用map來對映節點值與陣列下標。如此做,在得到一個值時,可快速得知其在陣列中(堆)的位置。
    //該位置的性質決定了它與其他節點的關係
    for (int i = 0; i < n; i++)
        mp[dataa[i]] = i;
    while (m--) {
        string a, b, c, d, e, f;//這裡進行字元讀取
        cin >> a >> b;
        if (b[0] == 'i') {
            //字元處理髮現語句規律
            cin >> c >> d;
            switch (d[0]) {
            case 'r':
                dataa[0] == atoi(a.c_str())? cout << 'T' : cout << 'F';
                break;
            case 'p':
                cin >> e >> f;
                ((mp[atoi(f.c_str())] - 1) / 2 == mp[atoi(a.c_str())]) ? cout << 'T' : cout << 'F';
                break;
            case 'c':
                cin >> e >> f;
                ((mp[atoi(a.c_str())] - 1)/ 2 == mp[atoi(f.c_str())]) ? cout << 'T' : cout << 'F';
                break;
            }
        }
        else {
            cin >> c>>d>>e;
            ((mp[atoi(a.c_str())] - 1) / 2 == (mp[atoi(c.c_str())] - 1) / 2 )? cout << 'T' : cout << 'F';
        }
        cout << endl;
    }
    return 0;
}
//end

謝謝觀看,如果有問題可評論提出。如果覺得有幫助,也十分感謝您的點贊!