PTA关于堆的判断
一、题目描述
二、解题思路
每次插入一个元素我就进行一次堆的调整,不要存着最后再进行堆调整。用一个map记录每个元素在队中的位置,剩下的就是读入的问题了。
三、代码实现
1 #include "bits/stdc++.h" 2 using namespace std; 3 const int inf = -1e9 + 10; 4 int heap[1010]; 5 map <int,int> mp; 6 void heapify(int idx) 7 { 8 if(idx == 1) 9 return; 10 while(idx > 1){ 11 if(heap[idx] < heap[idx / 2]) 12 swap(heap[idx],heap[idx / 2]); 13 else 14 break; 15 idx /= 2; 16 } 17 } 18 int main() 19 { 20 int n,m; 21 cin >> n >> m; 22 for(int i = 1;i <= n;i++){ 23 cin >> heap[i]; 24 heapify(i); 25 } 26 for(int i = 1;i <= n;i++) 27 mp[heap[i]] = i; 28 while(m--){ 29 int val1; 30 int val2; 31 string s; 32 cin >> val1; 33 cin >> s; 34 if(s == "and"){ 35 cin >> val2; 36 getline(cin,s); 37 int i; 38 if(mp[val1] / 2 == mp[val2] / 2) 39 cout << "T" << endl; 40 else 41 cout << "F" << endl; 42 } 43 else{ 44 cin >> s; 45 if(s == "the"){ 46 cin >> s; 47 if(s == "root"){ 48 if(mp[val1] == 1) 49 cout << "T" << endl; 50 else 51 cout << "F" << endl; 52 } 53 else if(s == "parent"){ 54 cin >> s; 55 cin >> val2; 56 int i; 57 if(mp[val2] / 2 == mp[val1]) 58 cout << "T" << endl; 59 else 60 cout << "F" << endl; 61 } 62 } 63 else if(s == "a"){ 64 cin >> s; 65 cin >> s; 66 cin >> val2; 67 if(mp[val1] / 2 == mp[val2]) 68 cout << "T" << endl; 69 else 70 cout << "F" << endl; 71 } 72 } 73 } 74 return 0; 75 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}