Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 35421 | Accepted: 12737 |
Description

在这个问题中,你将需要分析一个排序算法,这个算法就是通过交换相邻两个数字来使一个无序的序列变的有序。比如一个输入序列
Ultra-QuickSort produces the output
Ultra-QuickSort produces the output
实用Ultra-QuickSort将得到输出
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
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.
输入包含多组手。每组数据的第一行包含一个整数n < 500,000--表示输出序列的长度。接下来n行包括一系列的整数0 ≤ a[i] ≤ 999,999,999。表示这个序列的第i个数字。如果这组数据第一个数n=0则输入结束。
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.
对于每一个输入,你的程序要输出一行包含一个整形数字op。表示这个排序需要的最小的相邻数字交换次数。
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
Source
好吧,我就是把所有需要用逆序数的题挑出来了做了一下,然后这个数据由于格外大,因此交了好几次t,虽然不知道为什么会t,我甚至把最大数组长度从555555改成500001就过了,于是我只能认为是我随意开的空间太大导致的......
也许大部分时间编译器都在努力的初始化.....
具体算法依然是归并排序,这个归并排序我是直接改的算法导论上面的.....用起来还行....就是每次都得改最大值.....
这里面要注意逆序数的值会超过int也就是32位数.....然后由于数组空间太大然后codeblocks无能为力.....
#include <iostream>
#include <cmath>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#define MAXINT 1111111111
#define LENGTH 500001
void Merge_sort(int a[LENGTH], int p, int r);
void Merge(int a[LENGTH], int p, int q, int r);
__int64 inve_sum = 0;
int main(void)
{
int a[LENGTH];
int number;
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while(scanf("%d", &number) && number){
for (int i = 0;i < number;i ++)
scanf("%d", &a[i]);
inve_sum = 0;
Merge_sort(a, 0, number-1);
printf("%I64d\n", inve_sum);
}
return 1;
}
void Merge_sort(int a[LENGTH], int p, int r){
int q;
if (p < r){
q = (p + r) >> 1;
Merge_sort(a, p, q);
Merge_sort(a, q + 1, r);
Merge(a, p, q, r);
}
}
void Merge(int a[LENGTH], int p, int q, int r){
int L[(LENGTH >> 1) + 1], R[(LENGTH >> 1) + 1];
int n1 = 0, n2 = 0;
for (int i = p;i <= q;i ++){
L[n1++] = a[i];
}
L[n1] = MAXINT;
for (int i = q + 1;i <= r;i ++){
R[n2++] = a[i];
}
R[n2] = MAXINT;
n1 = 0, n2 = 0;
for (int k = p;k <= r; k++){
if (L[n1] <= R[n2]){
a[k] = L[n1];
n1++;
}else{
a[k] = R[n2];
inve_sum += q - p + 1 - n1;
n2++;
}
}
}