D - Ultra-QuickSort
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
题目大意:
给定一个序列,然后再给你一个通过归并排序后的序列,
要你给出这个步骤中最小的交换次数。
思路:
其实题目的思路就是求解逆序数
对应的,我们可以想到使用树状数组BIT进行求解,那么具体的怎么求呢?
首先要知道树状数组能够干什么?他是一个能够完成一个以下操作的数据结构
给定 一个初始全为0的数列 a1,a2,,,,an
1.给定i ,计算 a1+a2+...+ai
2.给定i和x,计算ai+=x
利用树状数组,我们每次可以插入这个值,记录到在比这个数小的所有插入数的总和 X
然后利用当前 的总共插入数的数量Z 来进行求解、
具体的 Z - X 就是当前逆序数的数量
3.另外,在使用这个数组的时候,要注意是否需要离散化,因为数据的间隔太过庞大,不利于树状数组的使用
所以思路是:
1. 建立一个结构题 ,记录 val 和pos 表示原来的序列的值和位置
2.通过对val 对其进行排序,排序之后就能得到这个序列的原来相对大小关系
3.通过这个原来相对大小关系,我们再对其进行赋值,就可以实现离散化。具体看代码
code:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int N;
const int MAXN = 5e5+10;
typedef long long ll;
struct node{
int val;
int pos;
}ori[MAXN];
int after[MAXN];
bool cmp(const node &a,const node &b){
return a.val<b.val;
}
int bit[MAXN];
void init(){
memset(bit,0,sizeof(bit));
}
//树状数组 的更新操作,将index 后的二进制为的最后有个 1的位置再添加 1
void add(int index){
while(index<=N){
bit[index]+=1;
//index&-index 就是 index 后的二进制为的最后一个 1
index+= index&-index;
}
}
//树状数组 求和操作, index 后的二进制为的最后有个 1的位置再减去 1
int sum(int index){
int ans = 0;
while(index>0){
ans+=bit[index];
index-=index&-index;
}
return ans;
}
int main(){
while(scanf("%d",&N)!=EOF){
if(N==0) break;
init();
//离散化 先根据原来的值将结构体进行排序
for(int i=1;i<=N;i++){
ori[i].pos = i;
scanf("%d",&ori[i].val);
}
sort(ori+1,ori+1+N,cmp);
//排完序之后,再根据原来的下标进行重新赋值,相当于保持了
//原来值的相对关系
for(int i=1;i<=N;i++){
after[ori[i].pos] = i;
}
ll ans=0;
for(int i=1;i<=N;i++){
add(after[i]);
// i-sum(after[i]) 就表示当前的总插入数量Z - 目前比这个数小的数量
//那么剩下的就是逆序数的数量
ans+=(i-sum(after[i]));
}
printf("%lld\n",ans);
}
return 0;
}