归并排序求逆序数对 hdu2689

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序求逆序数对 hdu2689相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

hdu 4911 Inversion(归并排序求逆序对数)2014多校训练第5场

白话经典算法系列之九 从归并排序到数列的逆序数对(微软笔试题)

HDU 4911 Inversion 树状数组求逆序数对

归并排序求逆序对

归并排序 之 逆序对

归并排序求逆序对