---
id: 316
lang: en
translation_of: index.md
source_sha256: bde8a745fba3363c118d1c949582f7a3e0c3fdbffd06a2472acdeb295439538b
title: "P1801: Black Box — Solution"
description: "Keep a max-heap and a min-heap: the max-heap holds i-1 numbers, so the i-th smallest sits at the top of the min-heap."
tags: ["OI","Heap","Two Heaps"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "对顶堆 (literally “heaps placed top to top”) rendered as “the two-heap structure”, matching the tag “Two Heaps”."
  - "The second paragraph says 第i大 (“i-th largest”) where the first says 第i小 (“i-th smallest”); kept as written."
---

## Main Idea

We can consider a <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">godlike</span> structure: the two-heap structure. Create a max-heap $qmax$ and a min-heap $qmin$. We first store the data in an array. Then, for a given query, we need to find, among the first $u(i)$ numbers of the whole sequence, the $i$-th smallest number. At each query, we put the first $u(i)$ numbers into the max-heap, and when the number of elements in the max-heap equals $i$, we move the largest number in the max-heap (the heap top) into the min-heap. In the end, the max-heap holds $i-1$ elements, and the $i$-th smallest number we are looking for must be at the top of the min-heap.

<!--more-->

Why? Because each time we move the top of the max-heap into the min-heap, which means every number in the min-heap is greater than every number in the max-heap. Then the max-heap maintains $i-1$ numbers, so the $i$-th largest number is naturally at the top of the min-heap.

## Code

```cpp
// P1801.cpp
#include <iostream>
#include <cstdio>
#include <queue>
#define ll long long
using namespace std;
const int maxn = 210000;
ll M, N, arr[maxn], num, idx = 0, r = 1;
priority_queue<ll> qmax;
priority_queue< ll, vector<ll>, greater<ll> > qmin;
int main()
{
    scanf("%lld%lld", &M, &N);
    for (int i = 1; i <= M; i++)
        scanf("%lld", &arr[i]);
    for (int i = 1; i <= N; i++)
    {
        scanf("%lld", &num), idx++;
        for (int prev = r; prev <= num; prev++)
        {
            qmax.push(arr[prev]);
            if (i == qmax.size())
                qmin.push(qmax.top()), qmax.pop();
        }
        r = num + 1;
        printf("%d\n", qmin.top()), qmax.push(qmin.top()), qmin.pop();
    }
    return 0;
}
```
