跳到正文

题解

题解:AT_abc452_f [ABC452F] Interval Inversion Count

IcyDragon约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年4月7日
收录
2026年4月7日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v1当前

思路

维护一个滑动窗口,记录区间 [l,r][l,r] 内的逆序对数量。

  • 当元素 Pr+1P_{r+1} 进入时,答案会增加窗口中比 Pr+1P_{r+1} 大的元素个数;
  • 当元素 PlP_l 离开窗口时,答案会减少窗口中比 PlP_l 小的元素个数。

可以用树状数组来维护窗口中的元素。

注意事项

  • 要开 long long,别开少了;
  • 可能需要卡常。

代码

记录

C++
#include<iostream>
#include<cstring>
#ifdef LOCAL
#define getchar_unlocked _getchar_nolock
#define putchar_unlocked _putchar_nolock
#endif
using namespace std;

typedef long long lld;

struct BIT{
	lld t[500010];
	int n;
	void clear(){
		memset(t,0,sizeof t);
	}
	inline int lowbit(int x){
		return x & -x;
	}
	void add(int x,lld k){
		for(; x <= n; x += lowbit(x)){
			t[x] += k;
		}
	}
	lld query(int x){
		lld s = 0;
		for(; x >= 1; x -= lowbit(x)){
			s += t[x];
		}
		return s;
	}
}t;
int a[500100],n;

template <typename Type = int>
Type read(){
	Type s=0,f=1;
	int c = getchar_unlocked();
	for(; !isdigit(c); c = getchar_unlocked()){
		if(c == '-'){
			f = -1;
		}
	}
	for(; isdigit(c); c = getchar_unlocked()){
		s = s*10+c-'0';
	}
	return s * f;
}
template<typename Type>
void write(Type i){
	if(i < 0){
		putchar_unlocked('-');
		i = -i;
	}
	if(i > 9){
		write(i/10);
	}
	putchar_unlocked((i%10)+'0');
}
lld get(lld k){
	if(k < 0){
		return 0;
	}
	t.n = n;
	t.clear();
	lld ans=0,s=0,r=0,_t;
	for(lld l = 1; l <= n; l++){
		while(r < n){
			_t = r-l+1-t.query(a[r+1]);
			if(s+_t > k){
				break;
			}
			s += _t;
			t.add(a[++r],1);
		}
		ans += r-l+1;
		s -= t.query(a[l]-1);
		t.add(a[l],-1);
	}
	return ans;
}

int main(){
	lld k;
	n=read();k=read<lld>();
	for(int i = 1; i <= n; i++){
		a[i] = read();
	}
	write(get(k)-get(k-1));
	return 0;
}