PAT005 Path in a Heap

题目:

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

分析:主要是考查最小堆的建立。

代码:

typedef struct heapNode {
    int elements[1000];
    int size;
    int capacity;
} MinHeapNode;

MinHeapNode *createHeap(int maxSize)
{
    MinHeapNode *heap = (MinHeapNode *)malloc(sizeof(MinHeapNode));
    heap->size = 0;
    heap->capacity = maxSize;
    heap->elements[0] = -10001; // 哨兵
    return heap;
}

void insertToMinHeap(MinHeapNode *heap, int item)
{
    if (heap->size == heap->capacity) {
        return; // 堆已满,无法插入
    }
    
    int i = ++heap->size;
    for (; heap->elements[i / 2] > item; i /= 2) {
        heap->elements[i] = heap->elements[i / 2];
    }
    heap->elements[i] = item;
}

int main()
{
    // 接受输入
    int itemNum, indexNum;
    scanf("%d %d", &itemNum, &indexNum);
    
    MinHeapNode *heap = createHeap(itemNum);
    for (int i = 0; i < itemNum; i++) {
        int item;
        scanf("%d", &item);
        insertToMinHeap(heap, item);
    }
    
    int a[indexNum];
    for (int i = 0; i < indexNum; i++) {
        int index;
        scanf("%d", &index);
        a[i] = index;
    }
    
    for (int i = 0; i < indexNum; i++) {
        int searchIndex = a[i];
        int flag = 1;
        while (searchIndex > 0) {
            if (flag) {
                printf("%d", heap->elements[searchIndex]);
                flag = 0;
            } else {
                printf(" %d", heap->elements[searchIndex]);
            }
            
            searchIndex /= 2;
        }
        printf("\n");
    }
}

运行结果:

posted @ 2015-04-06 13:08  2020_xx  阅读(280)  评论(0编辑  收藏  举报