7-11 关于堆的判断 (25 分) (建堆)


 

 要学会建堆,然后知道用数组模拟堆的优点。

#include 
#include 
#include 
using namespace std;
const int N = 1010;
int heap[N];
int n, m;

void insert(int pos, int x)  // 建堆
{
    heap[pos] = x;
    while(pos > 1) {
        if(heap[pos] < heap[pos >> 1]) {
            swap(heap[pos], heap[pos >> 1]);
            pos >>= 1;
        } else {
            break;
        }
    }
}
int main()
{
    cin >> n >> m;
    map<int,int>p;  // 用map 来 记录每个节点对应在数组中的下标
    for(int i = 1; i <= n; i++)
    {
        int x;
        cin >> x;
        insert(i, x);
    }
    
    for(int i = 1; i <= n; i++) p[heap[i]] = i;
    
    while(m--)
    {
        string s;
        int x, y, flag = 0;
        cin >> x >> s;
        if(s == "and") {                         // 根据每句话的特性来判断。 我觉得这非常妙
            cin >> y >> s >> s;
            if(heap[p[x] ^ 1] == y) flag = 1;
        } else {
            cin >> s;
            if(s == "a") {
                cin >> s >> s >> y;
                if(heap[p[x] >> 1] == y) flag = 1;
            } else {
                cin >> s;
                if(s == "root") {
                    if(heap[1] == x) flag = 1;
                } else {
                    cin >> s >> y;
                    if(heap[p[y] >> 1] == x) flag = 1;
                }
            }
        }
        if(flag) cout << "T" << endl;
        else cout << "F" << endl;
    }
    return 0;
}