PAT甲级1147 Heaps

冷不防 2023-02-19 09:24 219阅读 0赞

在这里插入图片描述
思路:
1.判断堆的类型通过按层序遍历顺序遍历一遍这棵树,如果子树结点值大于根,则maxheap置为false;类似的,如果子树结点值小于根,则minheap置为false
最后根据minheap和maxheap的值输出相应结果
2.后序遍历就是常规的方法,不同在于堆结构在数组中实现,根据下标遍历

代码

  1. #include<iostream>
  2. #include<vector>
  3. #include<queue>
  4. using namespace std;
  5. vector<int> v,sequence;
  6. bool maxheap=true,minheap=true;
  7. void judge(int low,int high)
  8. {
  9. queue<int> q;
  10. q.push(low);
  11. while(!q.empty())
  12. {
  13. int qq=q.front();
  14. q.pop();
  15. //if(!minheap&&!maxheap)break;
  16. if(qq*2<=high)
  17. {
  18. q.push(qq*2);
  19. if(v[qq*2]<v[qq])minheap=false;
  20. if(v[qq*2]>v[qq])maxheap=false;
  21. }
  22. if(qq*2+1<=high)
  23. {
  24. q.push(qq*2+1);
  25. if(v[qq*2+1]<v[low])minheap=false;
  26. if(v[qq*2+1]>v[low])maxheap=false;
  27. }
  28. }
  29. }
  30. void post(int index,int high)//后序遍历
  31. {
  32. if(index*2<=high)post(index*2,high);
  33. if(index*2+1<=high)post(index*2+1,high);
  34. sequence.push_back(v[index]);
  35. return;
  36. }
  37. int main()
  38. {
  39. int m,n;
  40. cin>>m>>n;
  41. v.resize(n+5);
  42. while(m--)
  43. {
  44. for(int i=1;i<=n;i++)cin>>v[i];
  45. maxheap=minheap=true;
  46. judge(1,n);
  47. if(maxheap)cout<<"Max Heap"<<endl;
  48. else if(minheap)cout<<"Min Heap"<<endl;
  49. else cout<<"Not Heap"<<endl;
  50. sequence.clear();
  51. post(1,n);
  52. for(int i=0;i<sequence.size();i++)
  53. {
  54. if(i!=sequence.size()-1)cout<<sequence[i]<<" ";
  55. else cout<<sequence[i]<<endl;
  56. }
  57. }
  58. return 0;
  59. }

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读