JOI '18 Open P1 - Bubble Sort 2

View as PDF

Submit solution


Points: 20 (partial)
Time limit: 2.5s
Memory limit: 512M

Problem type
Allowed languages
C, C++

Bubble sort is an algorithm to sort a sequence. Let's say we are going to sort a sequence A0,A1,,AN1 of length N in non-decreasing order. Bubble sort swaps two adjacent numbers when they are not in the correct order. Swaps are done by repeatedly passing through the sequence. Precisely speaking, in a pass, we swap Ai and Ai+1 if Ai>Ai+1, for i=0,1,,N2 in this order. It is known that any sequence can be sorted in non-decreasing order by some passes. For a sequence A, we define the number of passes by bubble sort as the number of passes needed to sort A using the above algorithm.

JOI-kun has a sequence A of length N. He is going to process Q queries of modifying values of A. To be specific, in the (j+1)-th query (0jQ1), the value of AXj is changed into Vj.

JOI-kun wants to know the number of passes by bubble sort for the sequence after processing each query.

Example

Given a sequence A={1,2,3,4} of length N=4 and Q=2 queries: X={0,2}, V={3,1}.

  1. For the first query, the value of A0 is changed into 3. We obtain A={3,2,3,4}.
  2. For the second query, the value of A2 is changed into 1. We obtain A={3,2,1,4}.

Bubble sort for A={3,2,3,4}:

  • A is not sorted, so the first pass starts. Since A0>A1, we swap them to get A={2,3,3,4}. Since A1A2, we don't swap them. Since A2A3, we don't swap them.
  • Now A is sorted, so the bubble sort ends.

Hence, the number of passes by bubble sort is 1 for A={3,2,3,4}.

Bubble sort for A={3,2,1,4}:

  • A is not sorted, so the first pass starts. Since A0>A1, we swap them to get A={2,3,1,4}. Since A1>A2, we swap them to get A={2,1,3,4}. Since A2A3, we don't swap them.
  • A is not sorted yet, so the second pass starts. Since A0>A1, we swap them to get A={1,2,3,4}. Since A1A2, we don't swap them. Since A2A3, we don't swap them.
  • Now A is sorted, so the bubble sort ends.

Hence, the number of passes by bubble sort is 2 for A={3,2,1,4}.

Subtasks

There are 4 subtasks. The score and the constraints for each subtask are as follows:

Subtask Score N Q A,V
1 17 1N2000 1Q2000 1Ai,Vj1000000000
2 21 1N8000 1Q8000 1Ai,Vj1000000000
3 22 1N50000 1Q50000 1Ai,Vj100
4 40 1N500000 1Q500000 1Ai,Vj1000000000

Implementation details

You should implement the following function countScans to answer Q queries.

Copy
std::vector<int> countScans(std::vector<int> A, std::vector<int> X, std::vector<int> V);
  • A: array of integers of length N representing the initial values of the sequence.
  • X, V: arrays of integers of length Q representing queries.
  • This function should return an array S of integers of length Q. For each 0jQ1, Sj should be the number of passes by bubble sort for the sequence right after processing (j+1)-th query.

Comments

There are no comments at the moment.