Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 59469 | Accepted: 22019 |
Description
In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Ultra-QuickSort produces the output
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
给一个数列,只能交换相邻的两个数,问完成一个递增排序最少转换多少次
归并排序即是把数列分为若干段,一段一段的查找,每段中查找左边比右边小的,交换过后就相当于本次查找中删除了这个数,因为左边的顺序已经排好,只需考虑右侧
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<map>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int maxn = 5e5+10;
int s[maxn], k[maxn];
LL ans;
void sor(int l, int r){
if(r-l <= 1) return;
int p, q, id, mid;
mid = l + (r-l)/2;
p = id = l; q = mid;
sor(l, mid); sor(mid, r);//分段
while(q < r || p < mid){//按段查找
if(q >= r || (p < mid && s[q] >= s[p])) k[id++] = s[p++];
else{
if(s[q] < s[p]) ans += mid-p;//两数的距离即是需要转换的次数
k[id++] = s[q++];
}
}
for(int i = l; i < r; i++) s[i] = k[i];//更新排好序的数列
}
int main(){
int t, n, kcase = 1;
while(scanf("%d", &n) == 1 && n){
for(int i = 0; i < n; i++) scanf("%d", &s[i]);
ans = 0;
sor(0, n);
cout << ans << endl;
}
return 0;
}