hust 1399 Is that a Heap?

题目描述

       Given a sequence S[1..N], you are to rearrange the sequence so that it satisfies the following condition: for each i (1 <= i <= N / 2), S[i] <= S[2*i] and S[i] <= S[2*i+1].

输入

       There are multiple test cases. For each case:

       The first line is a integer N. You are guaranteed that N = 2- 1 for some non-negative number m.

       The next line contains N numbers representing S[i]

       1 <= N <= 65535, S[i] <= 1,000,000,000

输出

       For each case, output the result sequence, if there are multiple solutions output the lexicographically largest one.

样例输入

3
1 2 10

样例输出

1 10 2
此题神题啊,题目保证n==2^m-1,这就是突破口啊
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

const int maxn=70000;
int a[maxn],ans[maxn];

void dfs(int p,int L,int R)
{
    ans[p]=a[L];
    if (L==R) return;
    dfs(p*2,(L+R)/2+1,R);
    dfs(p*2+1,L+1,(L+R)/2);
}

int main()
{
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        for (int i=1;i<=n;i++) scanf("%d",&a[i]);
        sort(a+1,a+n+1);
        dfs(1,1,n);
        printf("%d",ans[1]);
        for (int i=2;i<=n;i++) printf(" %d",ans[i]);
        printf("\n");
    }
    return 0;
}

 

今天又看了看这个题,感觉又不会做了,真是晕,现在总觉一下,首先必须看到n是什么,这样我们可以先看看n=3,n=7,n=15的情况,可以只用下标,甚至可以看看n=31的情况,因为我们只要字典系最小的解,故n=31我们是可以弄出来的,这样我想这个题的思想就直接出来了,果然是一道神题,我觉得这样的题是最有意思的,今天无意中又看到,感觉不会,于是就看了看自己的代码,发现不懂了,于是根据代码,打了一下表,才明白,搞ACM的千万别这样,在比赛时看到做过的题,但是突然想不到怎么做是件让人无法忍受的事,不过这个时候不要灰心,因为你做过嘛,证明你会做,所以再认真思考,一定可以的

posted @ 2014-05-15 08:35  Hust_BaoJia  阅读(124)  评论(0编辑  收藏  举报
努力