L2-012. 關於堆的判斷

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

  • “x is the root”:x是根結點;
  • “x and y are siblings”:x和y是兄弟結點;
  • “x is the parent of y”:x是y的父結點;
  • “x is a child of y”:x是y的一個子結點。

輸入格式:

每組測試第1行包含2個正整數N(<= 1000)和M(<= 20),分別是插入元素的個數、以及需要判斷的命題數。下一行給出區間[-10000, 10000]內的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

思路:邊輸入邊建堆,建堆的時候對堆進行調整,調整的時候只需要與他的父節點進行比較,一直把當前的這個結點調到他合適的位置,因爲結點的範圍是[-10000, 10000],所以後面用map把節點的值和位置進行對應一下,在後面判斷關係的時候直接用節點值的位置進行判斷。由小頂堆的性質可知下面的判斷方法是正確的;

1.如果該節點是父親節點,則該節點的下標爲1

2.如果兩個結點是兄弟,那麼他們的父親節點一定一樣

3.父節點的下標是子節點的1/2;

在輸入關係的時候可以把一句話每次判斷在分別輸入每句話的信息,這樣就可以把整數和字符串分開。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>

using namespace std;
const int maxn=1050;
int a[maxn];
int n,m,cnt;
//int idx[maxn];
map<int,int> idx;
void Build(int id)
{
    int val=a[id];
    int pos=id;
    while(pos>1&&val<a[pos/2])
    {
        a[pos]=a[pos/2];
        pos=pos/2;
    }
    a[pos]=val;
}
void charu(int x)
{
    a[++cnt]=x;
    Build(cnt);
}
int main()
{
    n=0;
    cin>>n>>m;
    for(int i=0; i<n; i++)
    {
        int x;
        cin>>x;
        charu(x);
    }
    for(int i=1; i<=cnt; i++)
    {
        idx[a[i]]=i;
    }
    for(int ka=0; ka<m; ka++)
    {
        int x;
        cin>>x;
        string s;
        cin>>s;
        if(s[0]=='a')
        {
            string ss,sss;
            int y;
            cin>>y;
            cin>>ss>>sss;
            int rx=idx[x];
            int ry=idx[y];
            if(rx/2==ry/2) cout<<"T"<<endl;
            else cout<<"F"<<endl;
        }
        else
        {
            string ss;
            cin>>ss;
            if(ss[0]=='a')
            {
                string s1,s2;
                cin>>s1>>s2;
                int y;
                cin>>y;
                int rx=idx[x];
                int ry=idx[y];
                if(rx/2==ry) cout<<"T"<<endl;
                else cout<<"F"<<endl;
            }
            else
            {
                string s1;
                cin>>s1;
                if(s1[0]=='r')
                {
                    int rx=idx[x];
                    if(rx==1) cout<<"T"<<endl;
                    else cout<<"F"<<endl;
                }
                else
                {
                    string s2,s3;
                    cin>>s2;
                    int y;
                    cin>>y;
//                    cout<<s2<<endl;
                    int rx=idx[x];
                    int ry=idx[y];
                    if(rx==ry/2) cout<<"T"<<endl;
                    else cout<<"F"<<endl;

                }
            }
        }
    }
}

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