poj2299--Ultra-QuickSort

来源:互联网 发布:宋慧乔整容了吗 知乎 编辑:程序博客网 时间:2024/05/22 21:12
Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 40285 Accepted: 14529

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

Source

Waterloo local 2005.02.05
给出n个数,每次只能交换两个相邻的数,交换最少次使得这n个数由小到大
这样交换,从第一个数开始,统计在这个数之前,且比这个数大的,一步一步的交换,使(包括这个数在内的)已交换的数是有序的,也就是说由左至右统计逆序数,
逆序数 = 在一串数中(对于每一位的,在该位之前且比这个数大的)个数的和 ;
同样也就可以理解为树状数组中统计每一位的值,该值为(在这一位之前,且比这个数小的),由这个数的序号-该值,最后累加得到整体的逆序数

#include <cstdio>#include <cstring>#include <algorithm>#include <map>using namespace std;map <int,int> s;int c[500010] , a[500010] , b[500010];int lowbit(int x){    return x & -x ;}void add(int i,int n){    while( i <= n )    {        c[i]++ ;        i += lowbit(i) ;    }}int sum(int i){    int a = 0 ;    while( i )    {        a += c[i] ;        i -= lowbit(i) ;    }    return a ;}int main(){    int i , n , num ;    while(scanf("%d", &n) && n)    {        memset(c,0,sizeof(c));        num = 0 ;        for(i = 0 ; i < n ; i++)        {            scanf("%d", &a[i]);            b[i] = a[i] ;        }        sort(a,a+n);        for(i = 0 ; i < n ; i++)            s[ a[i] ] = i+1 ;        for(i = 0 ; i < n ; i++)        {            num += ( i-sum( s[ b[i] ] ) ) ;            add(s[ b[i] ],n);        }        printf("%d\n", num);    }    return 0;}


0 0
原创粉丝点击