zoukankan      html  css  js  c++  java
  • L2-012 关于堆的判断 (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),分别是插入元素的个数、以及需要判断的命题数。下一行给出区间[−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
    

    分析:根据输入依次在堆中插入元素建立小顶堆,因为判断元素间关系需要用位置做判断,因此通过 unordered_map 记录每个元素的数组中的序号,在接收到命题之后直接取出元素对应的位置 pos 就行了。

    #include <bits/stdc++.h>
    using namespace std;
    vector<int> heap;
    int len = 0;
    void insert(int x) {
        int hole = ++len;
        for (; hole > 1 && heap[hole / 2] > x; hole /= 2)
            heap[hole] = move(heap[hole / 2]);
        heap[hole] = move(x);
    }
    int main() {
        int n, m, a, b;
        scanf("%d%d", &n, &m);
        heap.resize(n + 1);
        for (int i = 0; i < n; i++) {
            scanf("%d", &a);
            insert(a);
        }
        unordered_map<int, int> pos;
        for (int i = 1; i <= n; i++) pos[heap[i]] = i;
        char temp[10];
        for (int i = 0; i < m; i++) {
            scanf("%d %s", &a, temp);
            if (strcmp(temp, "and") == 0) {
                scanf("%d %*s %*s", &b);
                printf("%c
    ", pos[a] / 2 == pos[b] / 2 ? 'T' : 'F');
            } else {
                scanf("%*s %s", temp);
                if (strcmp(temp, "root") == 0) printf("%c
    ", a == heap[1] ? 'T' : 'F');
                else {
                    scanf("%*s %d", &b);
                    if (strcmp(temp, "parent") == 0) printf("%c
    ", pos[a] == pos[b] / 2 ? 'T' : 'F');
                    else
                        printf("%c
    ", pos[b] == pos[a] / 2 ? 'T' : 'F');
                }
            }
        }
        return 0;
    }
    

    The desire of his soul is the prophecy of his fate
    你灵魂的欲望,是你命运的先知。

  • 相关阅读:
    springmvc与ajax交互
    [PAT] A1052 Linked List Sorting
    [PAT] A1032 Sharing
    [PAT] A1076 Forwards on Weibo
    [PAT] A1034 Head of a Gang
    [PAT] A1030 Travel Plan
    [PAT] A1031 Hello World for U
    [PAT] A1029 Median
    [PAT] A1028 List Sorting
    [PAT] A1026 Table Tennis
  • 原文地址:https://www.cnblogs.com/RioTian/p/14691320.html
Copyright © 2011-2022 走看看