Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 69643 | Accepted: 26107 |
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
PS:因为数据很多不能暴力跑,所以只能用树状数组。树状数组求逆序数原理。这个需要用到离散化,
建立一个结构体包含val和id, val就是输入的数,id表示输入的顺序。然后按照val从小到大排序,如果val相等,那么就按照id排序。如果没有逆序的话,肯定id是跟i(表示拍好后的顺序)一直一样的,如果有逆序数,那么有的i和id是不一样的。所以,利用树状数组的特性,我们可以简单的算出逆序数的个数。
如果还是不明白的话举个例子。(输入4个数)
输入:9 -1 18 5
输出 3.
输入之后对应的结构体就会变成这样
val:9 -1 18 5
id: 1 2 3 4
排好序之后就变成了
val : -1 5 9 18
id: 2 4 1 3
2 4 1 3 的逆序数 也是3
之后再利用树状数组的特性就可以解决问题了;
因为数字可能有重复, 所以添加操作不再单纯的置为1 ,而是 ++;
AC代码:
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
#include<map>
#include<cmath>
#include<vector>
const int maxn=5e5+5;
const int mod=1e9+7;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
int bit[maxn],n;
struct node
{
int x,i;
bool friend operator<(node a,node b)
{
if(a.x==b.x)
return a.i<b.i;
return a.x<b.x;
}
}a[maxn];
int lowbit(int x)
{
return x&(-x);
}
void updata(int x)
{
while(x<=n)
{
bit[x]+=1;
x+=lowbit(x);
}
}
int ss(int x)
{
int s=0;
while(x)
{
s+=bit[x];
x-=lowbit(x);
}
return s;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
me(bit,0);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].x);
a[i].i=i;
}
sort(a+1,a+1+n);
ll sum=0;
for(int i=1;i<=n;i++)
{
updata(a[i].i);
sum+=i-ss(a[i].i);
}
cout<<sum<<endl;
}
return 0;
}