zoukankan      html  css  js  c++  java
  • L2-012 关于堆的判断 模拟堆

    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
    

    作者:陈越
    单位:浙江大学
    代码长度限制:16 KB
    时间限制:400 ms
    内存限制:64 MB



    PZ's Question

    1.这道题可以使用模拟小根堆的方法通过,对于某个键值的询问,可以使用STL——map解决;

    2.但是,为什么不能直接排序,然后对每个值进行标号呢?小根堆本来就不一定是一样的,所以感觉很神奇,或许这就是这道题的考点,也或许对于给定数字的插入顺序,小根堆排序结果是不同的……

    3.不论怎样,过了就是坠吼的!


    PZ.cpp

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<map>
    using namespace std;
    string s;
    int q[1005],top;
    map<int,int>num;
    void push(int x){
    	q[++top]=x;
    	num[x]=top;
    	int tmp=top,fa=top>>1;
    	while(tmp!=1 && q[fa]>q[tmp]){
    		swap(num[q[fa]],num[q[tmp]]);
    		swap(q[fa],q[tmp]);
    		tmp=fa; fa>>=1;
    	}
    }
    int main(){
    	int n,m,x,y;
    	scanf("%d %d",&n,&m);
    	while(n--){
    		scanf("%d",&x);
    		push(x);
    	}
    	cout<<num[46]<<endl;
    	while(m--){
    		scanf("%d",&x); cin>>s;
    		if(s[0]=='i'){
    			cin>>s>>s;
    			if(s=="root") cout<<(num[x]==1 ? "T" : "F")<<endl;
    			if(s=="parent"){
    				cin>>s; scanf("%d",&y);
    				cout<<(num[x]==(num[y]>>1) ? "T" : "F")<<endl;
    			}
    			if(s=="child"){
    				cin>>s; scanf("%d",&y);
    				cout<<((num[x]>>1)==num[y] ? "T" : "F")<<endl;
    			}
    		} else {
    			scanf("%d",&y); cin>>s>>s;
    			cout<<((num[x]>>1)==(num[y]>>1) ? "T" : "F")<<endl;
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    AJAX异步传输——以php文件传输为例
    js控制json生成菜单——自制菜单(一)
    vs2010中关于HTML控件与服务器控件分别和js函数混合使用的问题
    SQL数据库连接到服务器出错——无法连接到XXX
    PHP错误:Namespace declaration statement has to be the very first statement in the script
    【LeetCode】19. Remove Nth Node From End of List
    【LeetCode】14. Longest Common Prefix
    【LeetCode】38. Count and Say
    【LeetCode】242. Valid Anagram
    【LeetCode】387. First Unique Character in a String
  • 原文地址:https://www.cnblogs.com/Potrem/p/L2_012.html
Copyright © 2011-2022 走看看