poj2299—Ultra-QuickSort

来源:互联网 发布:nodejs 调用php接口 编辑:程序博客网 时间:2024/05/18 15:29
Ultra-QuickSort
Time Limit:7000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit
 
Status
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
5
9
1
0
5
4
3
1
2
3
0
Sample Output
6

0




题目大意:交换相邻的两个数,求最小的操作数使该数组变成上升数组

思路:用归并排序求逆序数。


#include <iostream>#include <cstdio>#include <cstring>using namespace std;typedef __int64 LL ;LL a[500005],vis[500005];LL ans;void sort2(LL a[], int begin, int mid, int end){     int i = begin; int j = mid + 1; int k = begin; while (i <= mid && j <= end) {     if(a[i] <= a[j]) {     vis[k++] = a[i++]; } else  {     vis[k++] = a[j++]; ans += mid - i +1; } } while(i <= mid) {     vis[k++] = a[i++]; } while (j <= end) {     vis[k++] = a[j++]; } for(i = begin; i <= end; i++) {     a[i] = vis[i]; }}void sort1(LL a[],int begin, int end){    if(begin != end){     int mid = (begin + end)/2; sort1(a,begin,mid); sort1(a,mid+1,end); sort2(a,begin, mid, end);}}int main(){    int n,i;while (scanf("%d",&n)&&n){ans = 0;     for(i = 0; i < n;i++){    scanf("%d",&a[i]);}sort1(a,0,n-1);printf("%I64d\n",ans);}    return 0;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 地下城老是闪退怎么办 强制关机后电脑打不开了怎么办 文明5地中海的海军怎么办 文明5被贸易禁运怎么办 文明5海里的食物怎么办 文明5遗址没了怎么办 ⅰpad屏幕动不了怎么办 苹果6plus满了怎么办 cf的fps低怎么办win7 游戏倒闭冲的钱怎么办 一闭眼就做噩梦怎么办 吃鸡游戏上瘾了怎么办 使命召唤7很卡怎么办 w10升级系统卡死怎么办 答题卡写错位置怎么办 高考答错区域该怎么办 荒野行动画面中间有条横怎么办 荒野行动pc闪退怎么办 幽灵行动荒野子弹没了怎么办 看门狗2枪没子弹怎么办 爱奇艺不小心删除了本地视频怎么办 80岁老太太就爱闹肚子怎么办? 皇牌空战5弹药不够怎么办 辐射4玩着头晕怎么办 官司打赢了法院不给钱怎么办 电脑玩dnf太卡怎么办 soul被禁止私聊怎么办 刺激战场空投挂树上怎么办 由于经济原因心态不好怎么办 公司经济不好不裁员怎么办 家里经济不好没有钱怎么办 银行柜员找不到工作怎么办 在球队中打替补怎么办 大学生毕业后找不到工作怎么办 30岁不敢换工作怎么办 投完简历没回复怎么办 工业废气一年总量超标怎么办 安监局行政处罚没能力交怎么办 被社会淘汰的人怎么办 宝宝吐奶的时候怎么办 网友要我发红包怎么办