版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tju_peter/article/details/79768420
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.
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.
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
Output for Sample Input
6 0
Source: Waterloo Local Contest Feb. 5, 2005
Problem ID in problemset: 1455
数的范围很大,但是只有500000个,学习了一下离散化
用一个struct存值和顺序,然后离散化的时候使用顺序就不会超过范围了。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
long long int c[500500];
int n;
struct s{
int v,order;
}a[500500];
int aa[500500];
int lb(int i)
{
return i&(-i);
}
int get(int i)
{
int ans=0;
while(i>0)
{
ans+=c[i];
i-=lb(i);
}
return ans; //有时候忘记写返回值,很蠢
}
void sets(int i,int x)
{
while(i<=n)
{
c[i]+=x;
i+=lb(i);
}
}
bool cmp(s a,s b)
{
if(a.v<b.v)
return 1;
return 0;
}
int main()
{
while(cin>>n)
{
memset(c,0,sizeof(c));
long long int ans=0;
if(n==0)
break;
for(int i=1;i<=n;i++)
{
cin>>a[i].v;
a[i].order=i;
}
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
aa[a[i].order]=i;
for(int i=1;i<=n;i++)
{
sets(aa[i],1);
ans+=(i-get(aa[i]));
}
cout<<ans<<endl;
}
return 0;
}