05-树6. Path in a Heap
来源:互联网 发布:数控西门子系统编程 编辑:程序博客网 时间:2024/05/16 09:33
Insert a sequence of given numbers into an initially empty min-heap H. Then for any given index i, you are supposed to print the path from H[i] to the root.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=1000) which are the size of the input sequence, and the number of indices to be checked, respectively. Given in the next line are the N integers in [-10000, 10000] which are supposed to be inserted into an initially empty min-heap. Finally in the last line, M indices are given.
Output Specification:
For each index i in the input, print in one line the numbers visited along the path from H[i] to the root of the heap. The numbers are separated by a space, and there must be no extra space at the end of the line.
Sample Input:5 3
46 23 26 24 10
5 4 3
Sample Output:24 23 10
46 23 10
26 10
这题属于二叉堆的练手题,开始以为二叉堆很难。 。结果发现还是比AVL和CBT容易一些。coding不到半小时就AC了。 。好久没有这么痛快了。
#include<stdio.h>int IsFull(int n,int i);void Insert(int* p,int k,int i);int main(){ int m,n,i,k; scanf("%d%d",&m,&n); int heap[m+1]; heap[0] = -20000;// 构建heap for(i = 1;i<=m;i++){ scanf("%d",&k); if(1 == i) heap[i] = k; else{ if(IsFull(m,i-1)) break; else Insert(heap,k,i); } }// 读取,输出 for(i = 0;i<n;i++){ scanf("%d",&k); for(int j = k;j;j/=2){ if(j == k) printf("%d",heap[j]); else printf(" %d",heap[j]); } if(i!=n-1) printf("\n"); } return 0;} void Insert(int* p,int k,int i){ for(;p[i/2]>k;i/=2) p[i] = p[i/2]; p[i] = k;}int IsFull(int n,int i){ if(n == i) return 1; return 0;}
- 05-树6. Path in a Heap
- 05-树6. Path in a Heap (25)
- 05-树6. Path in a Heap (25)
- 04-树9. Path in a Heap (25)
- PAT 数据结构 04-树9. Path in a Heap (25)
- 04-树9. Path in a Heap (25)
- 04-树9. Path in a Heap (25) -- 小堆树-利用其性质
- Dijkstra+Heap-HDU-4725-The Shortest Path in Nya Graph
- SPOJ 1437 Longest path in a tree
- leetcode Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- [LeetCode] Longest Increasing Path in a Matrix
- Longest Increasing Path in a Matrix
- leetcode: Longest Increasing Path in a Matrix
- Leetcode: Longest Increasing Path in a Matrix
- Longest Increasing Path in a Matrix
- leetcode:Longest Increasing Path in a Matrix
- [LeetCode]Longest Increasing Path in a Matrix
- java抓取网页代码
- Coarse-to-fine CNN 人脸特征点定位思路
- ubuntu 14.04 ssh
- [ATL/WTL]_[初级]_[SDI程序关闭的注意事项]
- Populating Next Right Pointers in Each Node II
- 05-树6. Path in a Heap
- APM_源码分析
- Ruby On Rails开发所需插件整理
- To The Max(hdu-1081)
- node.js用户注册功能的完善
- 统一认证系统实现要点-资源认证
- 《标记》-编码一次,解码两次?
- PHP字符串分割函数explode,strtok,str_spli的用法
- Ubuntu下搭建Ruby On Rails开发环境