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 1Sample Output
1 2 題意:相鄰的最多調(diào)換k次,使得逆對數(shù)最小, 思路,先求出整個(gè)序列的逆對數(shù)-k次就可,如果出現(xiàn)負(fù)數(shù)就輸出為0.用歸并排序求逆對數(shù)。值得注意的是千萬不要使用暴力會超時(shí),還有就要使用long long型不能也不行。輸出也是一個(gè)值得注意地方。 程序代碼: #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\n");else printf("%I64d\n",ans-k);}return 0; }?
?轉(zhuǎn)載于:https://www.cnblogs.com/yilihua/p/4713239.html
總結(jié)
- 上一篇: 界面随键盘顶起来
- 下一篇: Git的GUI工具sourcetree的