「SP25784」BUBBLESORT - Bubble Sort 解题报告
SP25784 BUBBLESORT - Bubble Sort
题目描述
One of the simplest sorting algorithms, the Bubble Sort, can be expressed as (0-based array):
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
Now, given an array of N integers, you have to find out how many swap opeartions occur if the Bubble Sort algorithm is used to sort the array.
输入输出格式
输入格式:
Input begins with a line containing an integer T(1<=T<=100), denoting the number of test cases. Then T test cases follow. Each test case begins with a line containing an integer N(1<=N<=10000), denoting the number of integers in the array, followed by a line containing N space separated 32-bit integers.
输出格式:
For each test case, output a single line in the format Case X: Y, where X denotes the test case number and Y denotes the number of swap operations needed modulo 10000007.
输入输出样例
输入样例#1:
1
4
3 2 1 4
输出样例#1:
Case 1: 3
思路
运用归并排序,求出逆序对即可。具体看代码注释。
代码
#include<bits/stdc++.h>
using namespace std;
#define mod 10000007
#define MAXN 10005
int T, N, ans;
int a[MAXN], b[MAXN];
void Merge_sort( int l, int r ){
if ( l == r ) return;//只有一个元素不用排序
int mid((l + r) >> 1);
Merge_sort( l, mid );//左边排序
Merge_sort( mid + 1, r );//右边排序
int i1(l), i2(mid + 1), c(l);//把左右两边归并
while( i1 <= mid && i2 <= r ){
if ( a[i1] <= a[i2] ) b[c++] = a[i1++];//必须写<=
else b[c++] = a[i2++], ans = ( ans + mid - i1 + 1 ) % mod;//顺便统计逆序对个数(右边元素之前有mid-i1+1个比它大的)
}
while( i1 <= mid ) b[c++] = a[i1++];//剩余的元素排到后面
while( i2 <= r ) b[c++] = a[i2++];
for ( int i = l; i <= r; ++i ) a[i] = b[i], b[i] = 0;//复制回原数组
}
int main(){
scanf( "%d", &T );
for ( int Ti = 1; Ti <= T; ++Ti ){
scanf( "%d", &N );
for ( int i = 1; i <= N; ++i ) scanf( "%d", &a[i] );
ans = 0;//初始化很重要
Merge_sort( 1, N );
printf( "Case %d: %d\n", Ti, ans );
}
return 0;
}