POJ 2299 Ultra-QuickSort

来源:互联网 发布:淘宝直通车关键词技巧 编辑:程序博客网 时间:2024/05/09 04:20

Ultra-QuickSort

Time Limit: 7000MSMemory Limit: 65536KTotal Submissions: 51274Accepted: 18803

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

这个题的尿性。。大概都集中在那个粉红的马桶刷子上了,或许应该配字,图与本题无关= =

题意是给定一串数字,每次只能移动相邻的数字。求需要移动多少次变成递增序列。

求需要移动多少次我们可以转化为求这串数字中的逆序对数,遇到这类问题,一般两种思路,第一种是归并排序的归并阶段,当ai < aj时,则有ai ~ an都是大于aj的。这样可以算逆序对数。

第二种思路就是树状数组,这个题给定的数太大,所以先离散一下,转换成存储着1~N的数组后进行树状数组操作,显然需要从后往前进行添加,比添加的当前数小的数的和就是这个数对应的逆序对数。代码如下:

/*************************************************************************> File Name: Ultra-QuickSort.cpp> Author: Zhanghaoran> Mail: chilumanxi@xiyoulinux.org> Created Time: 2016年02月03日 星期三 18时14分36秒 ************************************************************************/#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <cstdlib>using namespace std;long long tree[500010];struct node{    long long num;    int pos;}nn[500010];long long tt[500010];int N;long long sum = 0;bool cmp(node a, node b){    return a.num < b.num;}void add(long long x){    while(x < 500010){        tree[x] ++;        x += x & -x;    }}long long check(long long x){    long long ss = 0;    long long tep = x;    while(x){        ss += tree[x];        x -= x & -x;    }    return ss;}int main(void){    while(scanf("%d", &N), N){        memset(tree, 0, sizeof(tree));        sum = 0;        for(int i = 1; i <= N; i ++){            scanf("%lld", &nn[i].num);            nn[i].pos = i;        }        sort(nn + 1, nn + N + 1, cmp);        for(int i = 1; i <= N; i ++){            tt[nn[i].pos] = i;        }        for(int i = N;  i >= 1; i --){            sum += check(tt[i]);            add(tt[i]);        }        cout << sum << endl;    }    return 0;}

 

查看原文:http://chilumanxi.org/2016/02/03/poj-2299-ultra-quicksort/

0 0
原创粉丝点击