Inversion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 3028 Accepted Submission(s): 1105
Problem Description
bobo 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.
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).
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.
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
对于有重复元素求逆序数的情况,sort可能会改变相同元素的相对位置,为此WA两次,应当使用stable_sort解决;另外:最后求出cnt,然后减去k即可,因为相邻转换最佳情况是逆序数-1,同时最后要判断值会不会小于0,如果小于0直接输出0。还有一种方法是求和的时候去重。
/*------------------Header Files------------------*/
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <ctype.h>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <vector>
#include <limits.h>
using namespace std;
/*------------------Definitions-------------------*/
#define LL long long
#define PI acos(-1.0)
#define INF 0x3F3F3F3F
#define MOD 10E9+7
#define MAX 100050
/*---------------------Work-----------------------*/
int n,k,tree[MAX];
struct node
{
int num,id;
}a[MAX];
bool cmp1(node a,node b)
{
return a.num<b.num;
}
bool cmp2(node a,node b)
{
return a.id<b.id;
}
int lowbit(int i)
{
return i&-i;
}
void update(int i,int num)
{
while(i<=n)
{
tree[i]+=num;
i+=lowbit(i);
}
}
int getsum(int i)
{
int sum=0;
while(i>=1)
{
sum+=tree[i];
i-=lowbit(i);
}
return sum;
}
void work()
{
while(scanf("%d%d",&n,&k)==2)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].num);
a[i].id=i;
}
stable_sort(a+1,a+n+1,cmp1); //未加stable,WA两次
a[0].num=INF;
for(int i=1;i<=n;i++) //离散化,要处理相同元素的情况
{
/*if(a[i].num==a[i-1].num) a[i].num=a[i-1].num;
else*/ a[i].num=i;
}
stable_sort(a+1,a+n+1,cmp2);
memset(tree,0,sizeof(tree));
LL cnt=0;
for(int i=1;i<=n;i++)
{
update(a[i].num,1);
cnt+=i-getsum(a[i].num);
}
cnt-=k;
if(cnt<=0) printf("0\n");
else printf("%I64d\n",cnt);
}
}
/*------------------Main Function------------------*/
int main()
{
//freopen("test.txt","r",stdin);
//freopen("cowtour.out","w",stdout);
//freopen("cowtour.in","r",stdin);
work();
return 0;
}