码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序求逆序数对 hdu2689

时间:2017-11-14 14:53:30      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:opera   swap   ace   using   namespace   lines   des   求逆   end   

1、链接:

http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=216322

2、题目:

Description

You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.

Input

The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
Output

For each case, output the minimum times need to sort it in ascending order on a single line.
Sample Input

3
1 2 3
4
4 3 2 1
Sample Output

0
6

解题分析:

题意:求逆序数的个数

解法:归并排序的应用

代码:

 

#include<string.h>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;

int sum;
int temp[1005];
int a[1005];
void Merge(int a[],int l,int mid,int r){
   int i=l,j=mid+1,k=0;
   while(i<=mid&&j<=r){
      if(a[i]<a[j]){
        temp[k++]=a[i++];
      }
      else{
        temp[k++]=a[j++];
        sum+=mid-i+1;
      }
   }
   while(i<=mid)  temp[k++]=a[i++];
   while(j<=r)    temp[k++]=a[j++];

   for(int i=l,k=0;i<=r;k++,i++)
    a[i]=temp[k];

}

void MergeSort(int a[],int l,int r){
   int mid;
   if(l<r){
       mid=(l+r)/2;
       MergeSort(a,l,mid);
       MergeSort(a,mid+1,r);
       Merge(a,l,mid,r);
   }
}
int main(){
   int n;

   while(scanf("%d",&n)!=EOF){
        sum=0;
      for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
      MergeSort(a,0,n-1);
      printf("%d\n",sum);

   }
   return 0;
}

 

归并排序求逆序数对 hdu2689

标签:opera   swap   ace   using   namespace   lines   des   求逆   end   

原文地址:http://www.cnblogs.com/hhkobeww/p/7831624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!