归并排序求逆序数——HDU 4911
来源:互联网 发布:阿里云cdn combo 编辑:程序博客网 时间:2024/06/04 19:16
对应HDU题目:点击打开链接
Inversion
Time Limit:1000MS Memory Limit:131072KB 64bit IO Format:%I64d & %I64uDescription
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.
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).
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.
A single integer denotes the minimum number of inversions.
Sample Input
3 12 2 13 02 2 1
Sample Output
12
因为是相邻元素互换,故每换一次都会减少一对逆序数。所以直接愉快地套汝佳哥归并排序部分代码求出逆序数cnt,
如果cnt-k<0,则肯定能把原序列换成递增,即没有逆序数,否则输出cnt-k。
#include <iostream>#include <cstring>#include <algorithm>#include <cstdio>using namespace std;#define LL long long int shu[100005],vis[100005];LL cnt=0;void mer(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;mer(A,x,m,t);mer(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){for(int i=1;i<=n;i++){scanf("%d",&shu[i]);}cnt=0;mer(shu,1,n+1,vis);if(cnt-k<0) printf("%d\n",0);else printf("%I64d\n",cnt-k);}}
0 0
- 归并排序求逆序数——HDU 4911
- hdu 4911 归并排序求逆序数
- hdu 4911 归并排序求逆序数
- HDU 4911 Inversion(归并排序求逆序数)
- HDU 4911 Inversion【归并排序求逆序数】
- HDU 4911 归并排序求逆序对
- nyoj117——用归并排序求逆序数
- 【nyoj117】—求逆序数(归并排序)
- 归并排序,求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- 归并排序求逆序数
- mount系统调用的实现
- iOS 自带的解析json的类
- android 编译sdk
- ubuntu下qq安装问题
- ios 读取项目下的文件
- 归并排序求逆序数——HDU 4911
- 华为OJ训练题之 比赛情况统计
- I am a newcomer
- apt软件包管理
- Mongodb 之insert瞬时完成,带测试数据---飞天博客
- sql的简单增删改查
- IOS开发系列--Objective-C之KVC、KVO
- 深刻理解Linux进程间通信(IPC)
- js获取非行间样式