7-3 堆中的路径 (25 分)

原文链接: http://www.cnblogs.com/sykline/p/10579014.html

题目:  

将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。

思路:

从当前的下标开始向前(堆顶)进行比较,如果上一层的值大于当前的值,就将上一层的值移动到当前的位置,知直到不能在移动为止。

代码:

#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <iomanip>
#define MAX 1000000000
#define inf 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
const int maxn = 10005;
int heap[maxn];
int n,m;

void insertHeap(int x,int level)
{
    while(level/2>0 && heap[level/2]>x)//如果上一层的值大于当前的值
    {
        heap[level] = heap[level/2];//将上一层的值向下移动
        level/=2;
    }
    heap[level] = x;//找到当前值该放的位置
    return;
}

void showPath(int level)
{
    printf("%d",heap[level]);
    level /= 2;
    while(level>0)
    {
        printf(" %d",heap[level]);
        level/=2;
    }
    printf("\n");
}

int main()
{
    int x;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
    {
        scanf("%d",&x);
        insertHeap(x,i);
    }
    for(int i=0; i<m; i++)
    {
        scanf("%d",&x);
        showPath(x);
    }
    return 0;
}

转载于:https://www.cnblogs.com/sykline/p/10579014.html

猜你喜欢

转载自blog.csdn.net/weixin_30319097/article/details/94789425