堆排WA 20pts求调
查看原帖
堆排WA 20pts求调
775325
colGem楼主2023/11/4 16:04
#include <stdio.h>

const int maxn = 100001;
int heap[maxn];
int size = 0;

void swap(int &a, int &b)
{
    int t = a;
    a = b;
    b = t;
    return;
}

void insert(int x)
{
    heap[++size] = x;
    int cur = size;
    while(cur / 2 && heap[cur/2] > heap[cur])
    {
        swap(heap[cur/2], heap[cur]);
        cur /= 2;
    }
    return;
}

int pop()
{
    int ans = heap[1];
    heap[1] = heap[size--];
    int cur = 1;
    while(2 * cur <= size)
    {
        int next = 2 * cur;
        if(next+1 <= size && heap[next+1] < heap[cur]) next++;
        if(heap[next] < heap[cur])
        {
            swap(heap[next], heap[cur]);
            cur = next;
        }
        else break;
    }
    return ans;
}

int main()
{
    int n, t;
    scanf("%d", &n);
    for(int i=0;i<n;i++)
    {
        scanf("%d", &t);
        insert(t);
    }
    for(int i=0;i<n;i++) printf("%d ", pop());
    return 0;
}

https://www.luogu.com.cn/paste/0lzdtqu8 https://www.luogu.com.cn/problem/P1177 https://www.luogu.com.cn/record/133303973

对了一下模板感觉堆没问题,也没TLE

2023/11/4 16:04
加载中...