Ultra-quicksort
Time Limit: 7000MS |
|
Memory Limit: 65536K |
Total Submissions: 43816 |
|
Accepted: 15979 |
Description
In this problem, you has to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping, 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 what many swap operations Ultra-quicksort needs to perform in order to sort a given input sequenc E.
Input
The input contains several test cases. Every test case begins with a line this contains a single integer n < 500,000-the length of the input sequence. Each of 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 is processed.
Output
For every input sequence, your program prints a single line containing an integer number OP, the minimum number of swap op Erations necessary to sort the given input sequence.
Sample Input
59105431230
Sample Output
60
Test instructions: Give a sequence number, each exchange adjacent numbers, to order the minimum number of exchanges in increments.
Idea: This should be a bubble sort, but the value is 50w, so it will definitely time out. Merge sort to order the number of reversed sequence, the number of reverse order = The number of sequential sequences can be obtained under the condition that only two adjacent elements are allowed to be exchanged.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm>using namespace Std;int input[500010];int Tmp[500010];long long sum;void merge (int l,int mid,int r) {int i=l; int j=mid+1; int k=1; while (i<=mid&&j<=r) {//This is where I and J Point are sorted and now merge if (Input[i]>input[j]) {tmp[k++]=input[ j + +]; sum+=mid-i+1;////I is larger than J because I have been from small to large row order so that i+1 to mid will also be larger than J} else tmp[k++]=input[i++]; } while (I<=mid) tmp[k++]=input[i++]; while (J<=R) tmp[k++]=input[j++]; for (i=l,k=1;i<=r;i++,k++) {input[i]=tmp[k]; }}void merge_sort (int l,int r) {if (l<r) {//length greater than 1 This is a judgment not loop int mid= (L+R)/2; Merge_sort (L,mid); Merge_sort (MID+1,R); Merge (L,mid,r); }}int Main () {int n,i; while (~SCANF ("%d", &n)} {if (n==0) break; for (i=0;i<n;i++) {scanf ("%d", &input[i]); } sum=0; Merge_sort (0,n-1); printf ("%lld\n", sum); } return 0;}
POJ 2299-ultra-quicksort (Merge sort to find the number of interchanges of neighboring elements)