博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ训练计划2299_Ultra-QuickSort(归并排序求逆序数)
阅读量:7060 次
发布时间:2019-06-28

本文共 1855 字,大约阅读时间需要 6 分钟。

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 39279   Accepted: 14163

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

Source

解题报告
求相邻的两两交换排序要几个步骤,就是求逆序数。
求逆序数的n方算法肯定超时,网上介绍了高速求逆序数的算法是用归并排序来实现的,时间复杂度是O(nlogn)。
刚学习了归并排序,这里不介绍归并排序。
为什么归并排序能够求逆序数。
在一个排列中,假设一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。依据归并排序,“划分”把序列分成元素个数尽量相等的两半,“递归”统计i和j均在左边或是均在右边的逆序对个数;“合并”统计i在左边,但j在右边的逆序数个数。
怎么统计逆序数个数呢?在归并排序合并操作时,因为是从小到大的排序,当A[j]复杂到T中时,左边还没有来得及复制的那些数就是左边全部比A[j]大的数。(以上i表示左区间数组的指针,j表示右区间数组指针,T是辅助空间,A是原数组)
这个题目要注意的是复杂空间必须开全局,局部可能溢出,还有答案要用longlong存。
#include 
using namespace std;long long a[500010],t[500010],cnt=0;void gbsort(long long *a,long long l,long long r){ if(l
>n) { if(!n)break; cnt=0; for(int i=0; i
>a[i]; gbsort(a,0,n-1); cout<
<

转载地址:http://njyll.baihongyu.com/

你可能感兴趣的文章
Python数据结构——树的实现
查看>>
iOS支付宝2.3.3SDK集成开发(Swift1.2)
查看>>
【memcache缓存专题(1)】memcache的介绍与应用场景
查看>>
JavaScript中Prototype、__proto__
查看>>
PaddlePaddle 中文名「飞桨」重磅公布,百度发布一亿元免费算力计划 ...
查看>>
kubernetes--应用程序健康检查
查看>>
学习大数据分析需要什么基础?
查看>>
iPhone XS选用英特尔基带的原因,苹果和高通的说法相互矛盾 ...
查看>>
jQuery事件对象---常见属性
查看>>
物联网数据可视化很难???你只需要它~~~
查看>>
三七女生节,看程序媛们选好口红色号,踩上高跟鞋,特别美丽,特别凶狠,特别温柔~ ...
查看>>
OTSReader自己定义切分主键
查看>>
免费直达国际顶会,与业界大佬面对面,AI 研习社 2019 年「顶会赞助计划」即将开启 ...
查看>>
关于人工智能,你所需了解的基本知识
查看>>
2019,聊聊Web技术的发展
查看>>
centos7使用kubeadm配置高可用k8s集群的另一种方式
查看>>
深入探索 Kdump
查看>>
three.js 坐标系、camera位置属性、点、线、面
查看>>
kubernetes1.9安装dashboard,以及token认证问题
查看>>
linux tcpdump
查看>>