堆中的路径 【Heap】

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

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

每组测试第1行包含2个正整数N和M(≤1000),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-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

思路
可以用STL 里面的 push_heap 来插入
然后 每次 下标/2 往上找就可以了

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-6;

const int INF = 0x3f3f3f3f;
const int maxn = 1e4 + 5;
const int MOD = 1e9 + 7;

vector <int> v;

void dfs(int x)
{
    if (x == 1)
    {
        printf("%d
", -v[x]);
        return;
    }
    else
    {
        printf("%d ", -v[x]);
        dfs(x / 2);
    }
}

int main()
{
    int n, m;
    v.push_back(0);
    scanf("%d%d", &n, &m);
    int num;
    map <int, int> vis;
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &num);
        v.push_back(-num);
        push_heap(v.begin() + 1, v.end());
    }
    for (int i = 0; i < m; i++)
    {
        scanf("%d", &num);
        dfs(num);
    }
}
原文地址:https://www.cnblogs.com/Dup4/p/9433214.html