zoukankan      html  css  js  c++  java
  • 7-3 堆中的路径 (25 分)

    题目:  

    将一系列给定数字插入一个初始为空的小顶堆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("
    ");
    }
    
    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;
    }
  • 相关阅读:
    Vue生命周期(转)
    Gulp的简单使用
    webpack的简单使用
    面试----手写正则表达式
    面试----你可以手写一个promise吗
    baidu.com跳转www.baidu.com
    php 操作时间、日期类函数
    php操作文件类的函数
    sphinx搜索 笔记
    bash下输入命令的几个常用快捷键
  • 原文地址:https://www.cnblogs.com/sykline/p/10579014.html
Copyright © 2011-2022 走看看