#include #include #include using namespace std;

// 定义小顶堆类 class MinHeap { private: vector heap; // 存储堆的数组

public: // 初始化堆 void initHeap(vector& nums) { heap = nums; make_heap(heap.begin(), heap.end(), greater()); }

// 判断x是否为根节点
bool isRoot(int x) {
    return heap[0] == x;
}

// 判断x和y是否为兄弟节点
bool areSiblings(int x, int y) {
    int xIndex = -1, yIndex = -1;
    for (int i = 0; i < heap.size(); i++) {
        if (heap[i] == x) {
            xIndex = i;
        }
        if (heap[i] == y) {
            yIndex = i;
        }
    }
    if (xIndex == -1 || yIndex == -1 || xIndex == yIndex) {
        return false;
    }
    if (xIndex % 2 == 0) {
        return yIndex == xIndex + 1;
    } else {
        return yIndex == xIndex - 1;
    }
}

// 判断x是否为y的父节点
bool isParent(int x, int y) {
    int xIndex = -1, yIndex = -1;
    for (int i = 0; i < heap.size(); i++) {
        if (heap[i] == x) {
            xIndex = i;
        }
        if (heap[i] == y) {
            yIndex = i;
        }
    }
    if (xIndex == -1 || yIndex == -1 || xIndex == yIndex) {
        return false;
    }
    return (xIndex - 1) / 2 == yIndex;
}

// 判断x是否为y的子节点
bool isChild(int x, int y) {
    int xIndex = -1, yIndex = -1;
    for (int i = 0; i < heap.size(); i++) {
        if (heap[i] == x) {
            xIndex = i;
        }
        if (heap[i] == y) {
            yIndex = i;
        }
    }
    if (xIndex == -1 || yIndex == -1 || xIndex == yIndex) {
        return false;
    }
    if (yIndex % 2 == 0) {
        return xIndex == 2 * yIndex + 1;
    } else {
        return xIndex == 2 * yIndex + 2;
    }
}

};

int main() { int N, M; cin >> N >> M;

vector<int> nums(N);
for (int i = 0; i < N; i++) {
    cin >> nums[i];
}

MinHeap minHeap;
minHeap.initHeap(nums);

for (int i = 0; i < M; i++) {
    string proposition;
    cin >> proposition;

    if (proposition == "is") {
        string relation;
        int x, y;
        cin >> x >> relation >> y;
        if (relation == "the") {
            if (minHeap.isRoot(x) && y == "root") {
                cout << "T\n";
            } else {
                cout << "F\n";
            }
        } else if (relation == "and") {
            if (minHeap.areSiblings(x, y)) {
                cout << "T\n";
            } else {
                cout << "F\n";
            }
        } else if (relation == "a") {
            if (minHeap.isChild(x, y)) {
                cout << "T\n";
            } else {
                cout << "F\n";
            }
        } else if (relation == "of") {
            if (minHeap.isParent(x, y)) {
                cout << "T\n";
            } else {
                cout << "F\n";
            }
        }
    }
}

return 0;
编写一个C++代码将一系列给定数字顺序插入一个初始为空的小顶堆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分别是插

原文地址: https://www.cveoy.top/t/topic/hCRg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录