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

刚学树状数组求逆序对,就是初始化c数组为0,从后遍历a数组从c上把a在的位置标个1,同时求前缀和,这个前缀和就是逆序对.
离散化很神奇,数变少了,但却不影响结果

#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
struct node{
   
	int x,y;
}a[500005];
int c[500005];
int n;
bool cmp(node a,node b){
   
		return a.x<b.x;
}
void add(int x,int y){
   
	for(;x<=n;x+=(x&-x))	c[x]+=y;
}
int ask(int x){
   
	int ans=0;
	for(;x;x-=(x&-x))	ans+=c[x];
	return ans;
}
int main(){
   
	while(scanf("%d",&n)!=EOF&&n){
   
		memset(c,0,sizeof(c));
		for(int i=1;i<=n;i++){
   
			scanf("%d",&a[i].x);
			a[i].y=i;
		}
		sort(a+1,a+n+1,cmp);
		long long ans=0;
		for(int i=n;i;i--){
   
			ans+=ask(a[i].y-1);
			add(a[i].y,1);
		}
		printf("%lld\n",ans);
	}
	return 0;
}
全部评论

相关推荐

牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
牛客154160166号:9月底还给我发短信,好奇怪,我24届的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务