zoukankan      html  css  js  c++  java
  • 堆中的路径

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

    输入格式:

    每组测试第1行包含2个正整数N和M(≤),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-10000, 10000]内的N个要被插入一个初始为空的小顶堆的整数。最后一行给出M个下标。

    输出格式:

    对输入中给出的每个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。

    输入样例:

    5 3
    46 23 26 24 10
    5 4 3
    

    输出样例:

    24 23 10
    46 23 10
    26 10
    代码:
    #include <iostream>
    #include <cstdio>
    
    using namespace std;
    void pocolate_up(int *h,int c) {
        while(c / 2 >= 1 && h[c / 2] > h[c]) {
            swap(h[c / 2],h[c]);
            c /= 2;
        }
    }
    void get(int *h,int d) {
        while(d >= 1) {
            printf("%d",h[d]);
            if(d > 1) putchar(' ');
            d /= 2;
        }
    }
    int main() {
        int n,m,c = 0,d;
        int h[1005];
        scanf("%d%d",&n,&m);
        for(int i = 0;i < n;i ++) {
            scanf("%d",&d);
            h[++ c] = d;
            pocolate_up(h,c);
        }
        for(int i = 0;i < m;i ++) {
            scanf("%d",&d);
            get(h,d);
            putchar('
    ');
        }
    }
  • 相关阅读:
    js前端分享功能
    git常用命令
    webstorm中.vue报错
    页面重绘重排
    浏览器渲染引擎总结
    javascript中的this总结
    cookie、session、sessionid 与jsessionid
    promise和Angular中的 $q, defer
    C++11之nullptr
    C++ 输入ctrl+z 不能再使用cin的问题
  • 原文地址:https://www.cnblogs.com/8023spz/p/10403411.html
Copyright © 2011-2022 走看看