Inversion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 4258 Accepted Submission(s): 1561
Problem 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.
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 1 2 2 1 3 0 2 2 1
Sample Output
1 2
Author
Xiaoxu Guo (ftiasch)
Source
题意:给一个序列,你有k次交换相邻两个数的机会,问k此操作之后逆序对的最小值.
题解:用线段树处理出最开始的逆序数,每次交换选择最大的一个往后移,也就是说每次交换都会减少一个逆序对.结果就是max(0,sum-k).
注意要先离散化.
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <queue>
#include <ctype.h>
#include <vector>
#include <queue>
#include <set>
#include <map>
using namespace std;
const long long MAXN=300000+10;
const long long INF=1e9+7;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
long long sum[MAXN<<2];
void pushUp(long long rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(long long l,long long r,long long rt)
{
sum[rt]=0;
if(l==r)
return;
long long m=(l+r)/2;
build(lson);
build(rson);
}
void update(long long p,long long l,long long r,long long rt)
{
if(l==r){
sum[rt]++;
return;
}
long long m=(l+r)>>1;
if(p<=m)
update(p,lson);
else
update(p,rson);
pushUp(rt);
}
long long query(long long L,long long R,long long l,long long r,long long rt)
{
if(L<=l&&R>=r)
return sum[rt];
long long m=(l+r)>>1;
long long ret=0;
if(L<=m)
ret+=query(L,R,lson);
if(R>m)
ret+=query(L,R,rson);
return ret;
}
long long a[MAXN];
long long b[MAXN];
map<long long,long long> m;
int main()
{
long long n,k;
while(scanf("%lld%lld",&n,&k)!=EOF)
{
m.clear();
long long sum=0;
long long cnt=0;
for(long long i=0;i<n;i++)
{
scanf("%lld",a+i);
b[i]=a[i];
}
sort(b,b+n);
int tot=1;
for(int i=0;i<n;i++){
if(i==0){
m[b[i]]=tot;
}
else if(b[i]==b[i-1]){
m[b[i]]=tot;
}else{
m[b[i]]=++tot;
}
}
build(1,tot,1);
for(int i=0;i<n;i++){
a[i]=m[a[i]];
sum+=query(a[i]+1,tot,1,tot,1);
update(a[i],1,tot,1);
}
if(sum>=k){
printf("%lld\n",sum-k);
}else{
printf("0\n");
}
}
}

本文介绍了一种通过线段树处理序列中的逆序对问题的算法,旨在找到经过有限次数相邻元素交换后逆序对数量的最小值。文章详细阐述了算法原理及其实现过程。
623

被折叠的 条评论
为什么被折叠?



