Rounds to collect numbers
Créé le : 4 février 2025
Créé le : 4 février 2025
You are given an array that contains each number between 1 \dots n exactly once. Your task is to collect the numbers from 1 to n in increasing order. On each round, you go through the array from left to right and collect as many numbers as possible. What will be the total number of rounds? Input The first line has an integer n: the array size. The next line has n integers x_1,x_2,\dots,x_n: the numbers in the array. Output Print one integer: the number of rounds. Constraints
1 \le n \le 2 \cdot 10^5
Example Input: 5 4 2 1 5 3
Output: 3
Analysis
We have a permutation of the numbers . We want to "collect" the numbers in ascending order (from up to ) by repeatedly scanning from left to right. Each scan (or round) allows us to pick up as many of the needed numbers in increasing order as we encounter them. Once we cannot proceed (i.e., we've passed a needed number), we have to start a new round.
A clean way to figure out how many rounds this process will take uses the following observation:
Hence, counting how many times (for ) tells us exactly how many "breaks" in the sequence we have—and thus how many times we need a new round.
Formally,
Step-by-Step Solution
Read input:
Record positions:
Create an array pos
of length (if using 1-based indexing) so that:
Concretely, if you read the array as (1-based):
pseudofor i in 1..n: pos[A[i]] = i
Count breaks:
Initialize rounds = 1
.
Then compare consecutive positions and for to .
Each time we find , it means we need another round:
pseudorounds = 1 for i in 1..(n-1): if pos[i] > pos[i+1]: rounds += 1
Print the result (rounds
).
Example Walkthrough
Consider the example:
textn = 5 A = [4, 2, 1, 5, 3]
We find the positions of each number (1-based indexing for clarity):
Compare positions for from to :
We have 2 "breaks" → total rounds = .
This matches the process of physically scanning the array in passes:
1
.2
then 3
.4
then 5
.Hence the answer is 3.
The total number of rounds equals:
To implement:
pos
so that pos[value] = index_of_that_value_in_A
.rounds = 1
.pos[i] > pos[i+1]
, increment rounds
.rounds
.This runs in time and space, which is efficient for .