Ultra-QuickSort
Time Limit: 7000MS
Memory Limit: 65536K
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
::本题其实就是要求出有多少逆序对。本题还要虚拟化,因为0<=a[i]<=999,999,999,开一个数组大小为1,000,000,000*4铁定超内存
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
long ll;
int maxn=555555;
int col[maxn<<2];
int a[maxn],b[maxn],n;
12:
int rt)
14: {
15: col[rt]=0;
return ;
int m=(r+l)>>1;
18: build(lson);
19: build(rson);
20: }
21:
int x)
23: {
int l=1,r=n;
while(l<=r)
26: {
int m=(l+r)>>1;
return m;
if(x>a[m]) l=m+1;
else r=m-1;
31: }
return 0;
33: }
34:
int rt)
36: {
37: col[rt]++;
return ;
int m=(l+r)>>1;
if(p<=m) update(p,lson);
else update(p,rson);
42: }
43:
int rt)
45: {
return col[rt];
int m=(l+r)>>1;
int ans=0;
if(p<=m)
50: ans=col[rt<<1|1]+query(p,lson);
else
52: ans=query(p,rson);
return ans;
54: }
55:
int main()
57: {
int i;
,&n),n)
60: {
61: build(1,n,1);
for(i=1; i<=n; i++)
63: {
,a+i);
65: b[i]=a[i];
66: }
//让数组a升序排序,那么等下b就可以通过a来求出对应的树是第几大(这算是虚拟化吧)
68: ll sum=0;
for(i=1; i<=n; i++)
70: {
int t=find(b[i]);
72: sum+=(ll)query(t,1,n,1);
73: update(t,1,n,1);
74: }
,sum);
76: }
return 0;
78: }