思路:
用归并排序的方法,先将数组向下拆分成一个数为一个单位为止,然后再向上合并成有序数组,直到合并成一个完整的有序数组。由于每两个需要进行合并的数组S1和S2都已经是有序的,当S1[i]>S2[j]时,说明S1[i+1~m]都大于S2[j],所以有m-i+1个逆序对,而S[i+1~m]同样也大于S2[j]之前的所有数,但是随着j的每次移动(仅当S1[i]>S2[j]时,j会发生移动),都会计算一遍m-i+1,所以已经得到在S2[j]之前所有逆序对的数目了,不必重复计算。
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<iostream>
#include<cstdio>
using namespace std;
int N,A[10050],T[10050],ans;
void merge_sort(int L,int R)
{
if(R<=L)
return;
int m=(L+R)/2;
merge_sort(L,m);
merge_sort(m+1,R);//递归归并排序
int i=L,j=m+1,cnt=0;
while(i<=m&&j<=R)
{
if(A[i]<A[j])
{
T[cnt++]=A[i++]; //T是临时存放数组
}
else
{
T[cnt++]=A[j++];
ans+=m-i+1;
}
}
while(i<=m)
{
T[cnt++]=A[i++];
}
while(j<=R)
{
T[cnt++]=A[j++];
}
for(i=0; i<cnt; i++)
A[i+L]=T[i]; //把排好序的数组T复制到原来数组A对应的区间中
}
int main()
{
while(cin>>N)
{
for(int i=0; i<N; i++)
scanf("%d",A+i);
ans=0;
merge_sort(0,N-1);
printf("%d\n",ans);
}
return 0;
}
变形
Inversion HDU - 4911
bobo has a sequence a 1,a 2,…,a n. He is allowed to swap two adjacent numbers for no more than k times.
Find the minimum number of inversions after his swaps.
Note: The number of inversions is the number of pair (i,j) where 1≤i<j≤n and a i>aj.
Input
The input consists of several tests. For each tests:
The first line contains 2 integers n,k (1≤n≤10 5,0≤k≤10 9). The second line contains n integers a 1,a 2,…,a n (0≤a i≤10 9).
Output
For each tests:
A single integer denotes the minimum number of inversions.
Sample Input
3 1 2 2 1 3 0 2 2 1
Sample Output
1 2
这道题说的是,只有k次交换相邻两个数的机会,求交换后逆序数对的个数。
首先要明确一点,仅仅交换相邻两个位置的数字,如a[i]与a[i+1],只会减少a[i]与a[i+1]这一个逆序数对,a[i]比a[i+2~end]大或小的数目不会减少,同理,a[i+1]比a[i+2~end]大或小的数目也不会减少。所以还是求出原数组中所有的逆序对数,ans-k即是交换k个相邻的两个数后得到的最少逆序数对的数目。