[POJ] 2299 -> Ultra-QuickSort

来源:互联网 发布:蜂窝数据栏下找不到app 编辑:程序博客网 时间:2024/05/22 15:50
Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 46284 Accepted: 16842

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
解题思路:
本题就是求逆序数,暴力算法要超时的,所以改成归并排序求逆序数的算法
Code:
#include <iostream>#include <iterator>using namespace std;#define MAXSIZE 500000int arr[MAXSIZE], a[MAXSIZE], b[MAXSIZE];__int64 sum = 0;void merge(int* arr, int left, int mid, int right){int i = 0, j = 0, k = left;while (k <= mid)a[i++] = arr[k++];k = mid + 1;while (k <= right)b[j++] = arr[k++];int len1 = mid - left + 1;int len2 = right - mid;i = 0; j = 0; k = left;while (i < len1 && j < len2){if (a[i] < b[j]) arr[k++] = a[i++];else {arr[k++] = b[j++];sum += len1 - i;}}while (i < len1) arr[k++] = a[i++];while (j < len2) arr[k++] = b[j++];}void mergeSort(int* a, int left, int right) {if (left < right){int mid = (left + right) / 2;mergeSort(a, left, mid);mergeSort(a, mid + 1, right);merge(a, left,mid, right);}}__int64 mergeSort(int* a, int len) {sum = 0;mergeSort(arr, 0, len - 1);return sum;}int main(){int n;while (cin >> n, n){for (int i = 0; i < n; ++i)cin >> arr[i];printf("%I64d\n", mergeSort(arr, n));}return 0;}


0 0
原创粉丝点击