HDU 4911

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
题意:相邻的最多调换k次,使得逆对数最小,
思路,先求出整个序列的逆对数-k次就可,如果出现负数就输出为0.用归并排序求逆对数。值得注意的是千万不要使用暴力会超时,还有就要使用long long型不能也不行。输出也是一个值得注意地方。
程序代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define M 100007
#define ll _int64
ll a[M],c[M],ans,k;
using namespace std;
void merg(ll a[],int first,int mid,int last,ll c[])
{
    int i=first,j=mid+1;
    int m=mid,n=last;
    k=0;
    while(i<=m||j<=n)
    {
        if(j>n||(i<=m&&a[i]<=a[j])) c[k++]=a[i++];
        else {
            c[k++]=a[j++]; ans+=(m-i+1);
        }
    }
    for(i=0;i<k;i++)
        a[first+i]=c[i];
}
void merge_sort(ll a[], int first,int last,ll c[])
{
    if(first<last)
    {
        int mid=(first+last)>>1;
        merge_sort(a,first,mid,c);
            merge_sort(a,mid+1,last,c);
        merg(a,first,mid,last,c);
    }
}
int main()
{
int  n;
    ll k;
    while(scanf("%d%I64d",&n,&k)!=EOF)
    {
        memset(a,0,sizeof(a));
    memset(c,0,sizeof(c));
    ans=0;
    for(int i=0;i<n;i++)
        scanf("%I64d",&a[i]);
    merge_sort(a,0,n-1,c);
    if(ans-k<=0)
        printf("0
");
    else printf("%I64d
",ans-k);
    }
    return 0;
}
 
原文地址:https://www.cnblogs.com/yilihua/p/4713239.html