hdu 4911 Inversion(求逆序數)

來源:互聯網
上載者:User

標籤:merge   逆序數   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=4911


InversionTime Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 528    Accepted Submission(s): 228

Problem Descriptionbobo has a sequence a1,a2,…,an. He is allowed to swap twoadjacent 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. InputThe 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). OutputFor each tests:

A single integer denotes the minimum number of inversions. Sample Input
3 12 2 13 02 2 1
 Sample Output
12
 AuthorXiaoxu Guo (ftiasch) Source2014 Multi-University Training Contest 5 
解法:求的所給序列的逆序數,然後減掉k,如果小於零就去零!

代碼如下:(歸併排序法)
#include<stdio.h>int is1[112345],is2[112345];// is1為原數組,is2為臨時數組,n為個人定義的長度__int64 merge(int low,int mid,int high){int i=low,j=mid+1,k=low;__int64 count=0;while(i<=mid&&j<=high)if(is1[i]<=is1[j])// 此處為穩定排序的關鍵,不能用小於is2[k++]=is1[i++];else{is2[k++]=is1[j++];count+=j-k;// 每當後段的數組元素提前時,記錄提前的距離}while(i<=mid)is2[k++]=is1[i++];while(j<=high)is2[k++]=is1[j++];for(i=low;i<=high;i++)// 寫回原數組is1[i]=is2[i];return count;}__int64 mergeSort(int a,int b)// 下標,例如數組int is[5],全部排序的調用為mergeSort(0,4){if(a<b){int mid=(a+b)/2;__int64 count=0;count+=mergeSort(a,mid);count+=mergeSort(mid+1,b);count+=merge(a,mid,b);return count;}return 0;}int main(){int n, x;__int64 k;__int64 sum;while(scanf("%d%I64d",&n,&k)!=EOF){for(int i=0;i<n;i++){scanf("%d",&x);is1[i] = x;}__int64 ans=mergeSort(0,n-1);sum=0;printf("%I64d\n",ans-k>0?ans-k:0); }return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.