题目描述
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.
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.
样例输入
5
9
1
0
5
4
3
1
2
3
0
样例输出
6
0
#include <bits/stdc++.h> #define ll long long #define met(a) memset(a,0,sizeof(a)); using namespace std; const int mod=1e9+7; int s[500010],aa[500010],n; struct node{int b,c;}; node a[500010]; int lowbit(int x) { return x&(-x); } void update(int x,int y) { while(x<=n) aa[x]+=y, x+=lowbit(x); } int sum(int x) { int t=0; while(x>=1) t+=aa[x],x-=lowbit(x); return t; } bool cmp(node x,node y) { return x.b<y.b; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); int i,j,k,m; ll cnt=0; met(a); while(cin>>n&&n) { cnt=0; for(i=1;i<=n;i++) { cin>>a[i].b; a[i].c=i; } sort(a+1,a+1+n,cmp); for(i=1;i<=n;i++) s[a[i].c]=i; met(aa); for(i=1;i<=n;i++) { update(s[i],1); cnt+=(i-sum(s[i])); } cout<<cnt<<endl; } return 0; }