3743加强版(有重复元素)(14年多校)(4911)

本文探讨了在给定序列中通过最多k次相邻元素交换来最小化逆序数的方法。详细介绍了如何使用稳定排序和树状数组进行高效计算,并提供了优化技巧和边界条件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
 

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.
 

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值