美文网首页
hdu4911:Inversion

hdu4911:Inversion

作者: mztkenan | 来源:发表于2017-06-09 10:05 被阅读10次

    Problem Description

    bobo has a sequence a1,a2,…,an. 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 ai>aj.

    Input

    The input consists of several tests. For each tests:

    The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,…,an (0≤ai≤109).

    Output

    For each tests:

    A single integer denotes the minimum number of inversions.

    #include <iostream>
    
    using namespace std;
    long long int merge(int *a,int start,int mid,int end,int *t){
        int i=start,j=mid+1,k=start;
        long long int cnt=0;
        while (i<=mid&&j<=end)
        {
            if(a[i]>a[j]){
                t[k++]=a[j++];cnt+=mid-i+1;
            }
            else{
                t[k++]=a[i++];
            }
        }
        while (i<=mid)
        {
            t[k++]=a[i++];
        }
        while (j<=end)
        {
            t[k++]=a[j++];
        }
        for (int i=start;i<=end;i++)  //这里忘了将临时数组的值还回去,这样每次白排序了
        {
            a[i]=t[i];
        }
        return cnt;
    }
    long long int  merge_sort(int *a,int start,int end,int *t ){
        int mid;
        long long int cnt=0;
        if(start==end){
            t[start]=a[start];
        }
        else{
            mid=(start+end)/2;
            cnt+=merge_sort(a,start,mid,t);//这里也要加cnt,每个递归的mergeSort的值都要加起来,为防止错误,最好用全局变量
            cnt+=merge_sort(a,mid+1,end,t);
            cnt+=merge(a,start,mid,end,t);
        }
        return cnt;
    }
    
    
    int main()
    {
        int n,k;
        long long int cnt;
        while (cin>>n>>k)
        {
            int a[n];
            int t[n];
            for (int i=0;i<n;i++)
            {
                cin>>a[i];
            }
            cnt=merge_sort(a,0,n-1,t);
            long long int result=((cnt-k)>=0)?(cnt-k):0;
            cout<<result<<endl;
    //        for (int i=0;i<n;i++)
    //        {
    //            cout<<t[i]<<" ";
    //        }
        }
    
        return 0;
    }
    
    
    

    注意事项

    1.一定要注意数字越界。。。。。int 和long我曹溢出了。。。0≤k≤109,cnt数字很大,longlongint和long,int的区别

    相关文章

      网友评论

          本文标题:hdu4911:Inversion

          本文链接:https://www.haomeiwen.com/subject/qnzzfxtx.html