hdu 4911Inversion

Description

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>a j.
 

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
題意:
給你n個數a1,a2,a3...an,要你求出它的逆序數,但是可以交換相鄰的兩個數不超過k次,要你求出最小逆序數。
思路:
如果用普通的搜索肯定會超時,這時我們可以考慮用歸併排序,參考算法競賽與入門經典(第二版)中的P225-227,求出其逆序數,但這並不是最後的結果,因爲題目要求是求出最小逆序數,我們可以這樣想,每交換一次(相鄰兩個數前面的數比後面的數大),逆序數小於一,所以先求出未交換之前的逆序數,然後再減去k,如果逆序數大於0,這就是最後結果,如果小於0,說明最後交換肯定是達到從小到大的排列順序,逆序數就爲0.
代碼:
#include<cstdio>
#include<cstring>
#include<algorithm>
int  A[500004],T[500004];
long long  cnt;
using namespace std;
void init(int n)
{
    for(int i=0;i<n;i++)
        scanf("%d",&A[i]);

}
void merge_sort(int *A,int x,int y,int *T)
{
    if(y-x>1)
    {
        int m=x+(y-x)/2;
        int p=x,q=m,i=x;
        merge_sort(A,x,m,T);
        merge_sort(A,m,y,T);
        while(p<m||q<y)
        {
            if(q>=y||(p<m&&A[p]<=A[q]))    T[i++]=A[p++];
            else
            {
                T[i++]=A[q++];
                cnt+=m-p;

            }

    }            for(i=x;i<y;i++)
                A[i]=T[i];
}
}
int main()
{
    int n,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
       init(n);
       cnt=0;
     memset(T,0,sizeof(T));
     merge_sort(A,0,n,T);//不能把n寫成n-1,否則會答案錯誤
     if(cnt-k>=0)
        cnt=cnt-k;
     else
        cnt=0;
   printf("%I64d\n",cnt);
    }

    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章