Time Limit: 7000MS | Memory Limit: 65536KB | 64bit IO Format: %lld & %llu |
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.
Ultra-QuickSort produces the output
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
Source
逆序数对和即求每个数前面大于它的个数之和-----或者求每个数后面小于它的个数之和--
因为n个数不同,所以可以将n个数离散化压缩为1-n的数。
然后从数组的后面开始--每次先求已插入的小于它的数(即树状数组1-它的和)
再将它插入树状数组---
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
int v,hao;
}p[500100];
bool cmp(node xx,node yy)
{
return xx.v<yy.v;
}
int shu[500500];
int c[500500],n;
int lowit(int xx){return xx&-xx;}
void Add(int xx)
{
for (xx;xx<=n;xx+=lowit(xx))
c[xx]++;
}
int Sum(int xx)
{
int lp=0;
for (xx;xx>0;xx-=lowit(xx))
lp+=c[xx];
return lp;
}
long long s;
int main()
{
while (scanf("%d",&n),n)
{
memset(c,0,sizeof(c));
for (int i=1;i<=n;i++)
{
scanf("%d",&shu[i]);
p[i].hao=i;
p[i].v=shu[i];
}
sort(p+1,p+n+1,cmp);
for (int i=1;i<=n;i++)
shu[p[i].hao]=i;
s=0;
for (int i=n;i>0;i--)
{
s+=Sum(shu[i]);
Add(shu[i]);
}
printf("%lld\n",s);
}
return 0;
}
还有一种简单的方法:点击打开链接
运用vector 和 upper();但是会超时--对付对时间没什么要求的可以---代码简短精炼