Ultra-QuickSort
| Time Limit: 7000MS | Memory Limit: 65536K | |
| Total Submissions: 43844 | Accepted: 15990 |
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 Ultra-QuickSort produces the output
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
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
题目大意:
给出一串n长度的数字,可以交换任意两个相邻的数字,最后使序列为非递减序列,问最小的交换次数。
分析:
刚开始写的时候按着分治的思想去考虑,首先想到的是快排的思想,敲出来之后提交发现TLE,原因是快排没法控制次数,当时写的是在一个while循环里进行快排,而且每次都要进行一次判定,时间复杂度很高。后来改用了归并的思想,效率大大的提高了,一次归并就能解决问题,不需要像快排那样无法控制次数。
代码:
#include <iostream> #include <string.h> #include <cstring> #include <string> #include <algorithm> #include <stack> #include <queue> #include <stdio.h> #include <stdlib.h> #include <cstdlib> #include <cmath> #include <math.h> #include <vector> #include <map> #include <time.h> #include <ctime> using namespace std; #define M 500005 int a[M]; int num1[M]; long long sum; void Merge(int num[],int low,int m,int high); //归并 void Msort(int num[],int low,int high); int main() { int n; while (scanf("%d", &n) != EOF) { if (n == 0) break; sum = 0; for (int i = 0; i < n; i++) scanf("%d", &a[i]); Msort(a,0,n-1); printf("%I64d\n", sum); } return 0; } void Merge(int num[],int low,int m,int high) { int i = low, j = m+1; int k = 0; while(i <= m && j <= high) { if(num[i] <= num[j]) { num1[k++] = num[i++]; } else { num1[k++] = num[j++]; sum += m - i + 1; } } while(i <= m) num1[k++] = num[i++]; while(j <= high) num1[k++] = num[j++]; for(k = 0, i = low; i <= high; k++,i++) num[i] = num1[k]; } void Msort(int num[],int low,int high) { int mid; if(low < high) { mid = (low+high)/2; //分治 Msort(num,low,mid); Msort(num,mid+1,high); Merge(num,low,mid,high); //合并 } }
168

被折叠的 条评论
为什么被折叠?



