Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 80376 Accepted: 30098
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.
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
题目大意:给我们一个长度为n的序列,采用某种快速排序(交换排序),问最小交换次数。
思路:一天下来就搞了两道题。。。唉。。。多半是废了。
首先因为是交换排序很容易想到用冒泡排序去模拟,果断mle了,这时需要考虑更高效的算法
最小交换次数就是这个序列的逆序数,这个百度有严格证明,我就不多说了,关键是怎么求出这个逆序数。有三种方法可以求逆序数,分别是归并排序,线段树(后续补上),今天写的是树状数组。
由于数据范围非常大,所以需要离散化一下。
然后依次入读每个点再询问,因为第i个点最有有i-1个逆序数,因为树状数组要计数,每次+1,所以我们假设第i个点有i个逆序数(多一个本身,这是我们自己抽象出来的,方便计算),然后第i个数的最多逆序数减去不是不是逆序数的数量,剩下的就是逆序数的数量,然后累加求和就行了。然后我们用树状数组sum[i]维护第i个数不是逆序数的数量,只有是在它之前出现的都不可能是它的逆序数,那么它不是逆序数++。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
typedef long long ll;
ll a[maxn],b[maxn];
ll sum[maxn];
ll k;
ll query(ll x){
ll ans=0;
for(;x;x-=(x&-x)){
ans+=sum[x];
}
return ans;
}
void add(ll x,ll v){
for(;x<=k;x+=(x&-x)){
sum[x]+=v;
}
}
/* 5 9 1 0 5 4 3 1 2 3 */
int main(){
ll n;
while(scanf("%lld",&n)&&n){
memset(sum,0,sizeof(sum));
for(ll i=0;i<n;i++){
scanf("%lld",&a[i]);
b[i]=a[i];
}
sort(b,b+n);
k=unique(b,b+n)-b;
ll ans=0;
for(ll i=0;i<n;i++){
ll x=lower_bound(b,b+k,a[i])-b;
x++;
add(x,1);
ans+=(i+1-query(x));
}
printf("%lld\n",ans);
}
}