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

来源:互联网 发布:淘宝改价新规则 编辑:程序博客网 时间:2024/05/04 04:31

题意:给你一个n个整数组成的序列,每次只能交换相邻的两个元素,问你最少要进行多少次交换才能使得整个整数序列上升有序。

思路:首先要知道怎么求逆序数,从左往右看每个数字,该元素左边值比他大的元素个数就是这个元素的逆序数。所有逆序相加就是整个序列的逆序.统计元素左边比它大的元素个数,是不是和UVA1428很像了,只不过之前求小的,现在求比它大的那么就是sum(n)-sum(a[i])就是了。题目还有个问题就是数据范围很大,达到了几十亿,可是元素个数却只有50万个,显然我们没有办法开几十亿的数组,所以可以将这50万个元素离散化一下,因为这里只考虑元素的相对大小不考虑别的。


#include <cstdio>#include <queue>#include <cstring>#include <iostream>#include <cstdlib>#include <algorithm>#include <vector>#include <map>#include <string>#include <set>#include <ctime>#include <cmath>#include <cctype>using namespace std;#define maxn 500000+10#define maxnn 100000+10#define LL long longint cas=1,T;LL a[maxn];LL b[maxn];int c[maxn];int maxx,n;int lowbit(int i){return i&(-i);}int sum(int i){int ans = 0;while (i){ans +=c[i];i-=lowbit(i);}return ans;}void add(int i,int d){while (i<=n){c[i]+=d;i+=lowbit(i);}}int main(){//freopen("in","r",stdin);while (scanf("%d",&n)!=EOF && n){for (int i = 1;i<=n;i++){scanf("%d",&a[i]);b[i] = a[i];}sort(a+1,a+1+n);        for (int i = 1;i<=n;i++){b[i] = upper_bound(a+1,a+n+1,b[i])-a-1;}/*for (int i = 1;i<=n;i++)printf("%d ",b[i]);*/memset(c,0,sizeof(c));LL ans = 0;for (int i = 1;i<=n;i++){add(b[i],1);ans+=sum(n)-sum(b[i]);}printf("%lld\n",ans);}//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);return 0;}


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

59105431230

Sample Output

60


0 0
原创粉丝点击