#P15810. [JOI 2013 Final] バブルソート
[JOI 2013 Final] バブルソート
Problem Description
Bubble sort is an algorithm for sorting a sequence. Suppose we want to sort an array of length in ascending order. Bubble sort checks two adjacent numbers, and if their order is incorrect, it swaps them. This process is done by scanning the array from front to back. That is, if there exists a position with , then swap these two numbers, and perform this check once for each in the order ; this is called one scan. It is known that repeating such scans times will sort the array in ascending order.
The number of swaps in bubble sort for the array means the number of integer swaps that occur when applying the above algorithm to . (Known bubble sort algorithms and their implementations may differ slightly in loop order, range, termination conditions, etc. However, it is known that when applied to the same array, the number of integer swaps does not change because of these differences.)
For example, the following program is a function written in C that sorts an integer array of length using bubble sort.
void bubble_sort(int *a, int n) {
int i, j;
for (i = 0; i < n - 1; ++i) {
for (j = 0; j < n - 1; ++j) {
if (a[j] > a[j + 1]) {
/* The following 3 lines correspond to one integer swap */
int x = a[j];
a[j] = a[j + 1];
a[j + 1] = x;
}
}
}
}
Task
You are given a sequence of length . Suppose we obtain a new sequence by swapping two integers at arbitrary positions in exactly once. Write a program to find the minimum possible number of swaps in bubble sort for the sequence . (Note that the two integers swapped at the beginning do not have to be adjacent.)
Input Format
Read the following data from standard input.
- The first line contains an integer . is the length of the sequence .
- In the next lines, the -th line () contains an integer . This represents the -th integer of the sequence .
Output Format
Output one line to standard output containing one integer, which is the minimum possible number of swaps in bubble sort for the sequence .
5
10
3
6
8
1
0
5
3
1
7
9
5
2
3
1
2
3
1
Hint
Sample Explanation 1
If you swap at the beginning of the sequence with at the end, then the sequence becomes a sorted sequence, and its number of swaps in bubble sort is .
Sample Explanation 2
If you swap the third number in the sequence with the last number , then becomes . The number of swaps in bubble sort for is .
Sample Explanation 3
Even if the sequence is already sorted at the beginning, you still must perform one swap when constructing .
Constraints
the length of the sequence
the value of the numbers in the sequence
Scoring
In the testdata for scoring, the part worth 10% satisfies , and for any (), we have .
In the testdata for scoring, the part worth 30% satisfies , and for any (), we have .
In the testdata for scoring, the part worth 80% satisfies that for any (), we have .
Translated by ChatGPT 5