Ultra-QuickSort(树状数组+离散化)

时间:2023-03-08 17:08:44
Ultra-QuickSort  POJ 2299
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 50495   Accepted: 18525

Description

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[i]存储比i小的数目.
离散化: 比如输入9 1 0 5 4,将其转化为 5 2 1 4 3,方便存储。
参考别人的代码,看了好半天!
 #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define LL long long
#define Max 500000+10
using namespace std;
struct node
{
int num,order;
};
int n;
int c[Max];
node in[Max];
int t[Max];
int cmp(node a,node b)
{
return a.num<b.num;
}
void add(int i,int a)
{
while(i<=n)
{
t[i]+=a;
i+=i&-i;
}
}
int sum(int i)
{
int s=;
while(i>=)
{
s+=t[i];
i-=i&-i;
}
return s;
}
int main()
{
int i,j;
freopen("in.txt","r",stdin);
while(~scanf("%d",&n)&&n)
{
memset(t,,sizeof(t));
for(i=;i<=n;i++)
{
scanf("%d",&in[i].num);
in[i].order=i;
}
sort(in+,in++n,cmp);
for(i=;i<=n;i++) /*离散化*/
c[in[i].order]=i;
LL s=;
for(i=;i<=n;i++)
{
add(c[i],);
s+=i-sum(c[i]);
// cout<<s<<endl; }
printf("%lld\n",s);
}
}