ACM题集:https://blog.csdn.net/weixin_39778570/article/details/83187443
Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 72150 Accepted: 27104
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
题意:选择排序交换次数
题解:使用归并排序或者树状树组求逆序对
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#define ll long long
#define fo(i,j,n) for(register int i=j; i<=n; ++i)
using namespace std;
const int maxn=5e5+5;
struct BIT{
int C[maxn],n;
void init(int a){
n=a;
memset(C,0,(n+2)*sizeof(int));
}
int lowbit(int x){
return -x&x;
}
void add(int x,int d){
while(x<=n){
C[x]+=d;
x += lowbit(x);
}
}
ll sum(int x){
ll ret = 0;
while(x>0){
ret += C[x];
x -= lowbit(x);
}
return ret;
}
}bit;
int n,a[maxn],buf[maxn];
ll cnt;
inline void merge(int L,int R,int mid){
int i=L,j=mid+1;
fo(k,L,R){
if(j>R || i<=mid&&a[i]<=a[j]) buf[k]=a[i++];
else buf[k]=a[j++], cnt+=mid-i+1; // a[i]~a[mid]都比a[j]大构成逆序对
}
fo(k,L,R)a[k]=buf[k];
}
void MergeSort(int L,int R){
if(L>=R)return;
int mid = (L+R)>>1;
MergeSort(L,mid);
MergeSort(mid+1,R);
merge(L,R,mid);
}
void solve(){
fo(i,1,n)scanf("%d",&a[i]);
cnt=0;
MergeSort(1,n);
printf("%lld\n",cnt);
}
struct node{int val,idx; }A[maxn];
bool cmp(const node &a,const node &b){return a.val<b.val;}
int index[maxn];
void solve1(){
bit.init(n); // 需要先初始化
ll ans = 0;
fo(i,1,n){
scanf("%d",&A[i].val);
A[i].idx=i;
}
sort(A+1,A+n+1,cmp);
fo(i,1,n){
index[A[i].idx]=i; // 数组的每一个数离散化为不同的数,1 1 2 2 离散化为 1 2 3 4(也可以离散化为有重的)
}
fo(i,1,n){
ans += i-1-bit.sum(index[i]); // i-1为前面的总数,sum(index[i])为前面小于等于自己的数,减法后为大于自己的数
//cout<< i<<":"<<bit.sum(index[i])<<" "<<bit.sum(index[i]-1)<<" "<< index[i]<<endl;
bit.add(index[i],1);
}
printf("%lld\n",ans);
}
int main(){
while(scanf("%d",&n)&&n){
// solve(); // 归并排序
solve1();// 树状树组
}
}