#P4379. [USACO18OPEN] Lemonade Line S

[USACO18OPEN] Lemonade Line S

Description

It is a hot summer day on the farm, and Farmer John is handing out lemonade to his NN cows! All NN cows (numbered 1N1 \dots N) like lemonade, though some like it more than others. Specifically, cow ii is willing to stand behind at most wiw_i other cows to get lemonade. All NN cows are currently out in the field, but as soon as Farmer John rings the cowbell, they will immediately head to the lemonade stand. They will all arrive before Farmer John begins distributing lemonade, and no two cows arrive at the same time. Additionally, when cow ii arrives, she joins the line if and only if there are at most wiw_i cows in the line.

Farmer John wants to prepare some amount of lemonade in advance, but he does not want to waste any. The number of cows who line up may depend on their arrival order. Please help him determine, over all possible arrival orders, the minimum possible number of cows that end up in line.

Input Format

The first line contains NN. The second line contains NN space-separated integers w1,w2,,wNw_1, w_2, \dots, w_N. The input guarantees 1N1051 \leq N \leq 10^5, and for each cow ii, 0wi1090 \leq w_i \leq 10^9.

Output Format

Output the minimum possible number of cows in line over all possible arrival orders.

5
7 1 400 2 2
3

Hint

For example, it is possible that only three cows end up in the line (which is also the minimum possible). Suppose the cows with w=7w = 7 and w=400w = 400 arrive first and wait in line. Then the cow with w=1w = 1 arrives and leaves because there are already 22 cows in line. Next, two cows with w=2w = 2 arrive; one stays in line and the other leaves.

Problem setter: Dhruv Rohatgi.

Translated by ChatGPT 5