其他分享
首页 > 其他分享> > 【逆序对】【树状数组+离散化】CF220E Little Elephant and Inversions

【逆序对】【树状数组+离散化】CF220E Little Elephant and Inversions

作者:互联网

目录

题目链接

题意:

给定长度为n的序列A,取两个断点l和r,求由A[1],A[2],...,A[l],A[r],A[r+1],..A[n]组成的新序列B且其逆序对不大于k对的个数。

思路:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1E5+500;
int n,k,A[N],B[N];
struct tr_array{
	int tot;
	static const int maxn = 1e5+500;
	int arr[maxn];
	int inline lowbit(int x)
	{
		return (-x)&x;
	}
	void inline add(int x,int num)
	{
		tot += num;
		for(;x<=maxn;x+=lowbit(x)) arr[x] += num;
	}
	int inline ask(int x)
	{
		int res = 0;
		for(;x;x-=lowbit(x)) res += arr[x];
		return res;
	}
}tr_l,tr_r;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	    cin>>A[i],B[i] = A[i];
	
	//离散化 
	sort(B+1,B+n+1);
	int tot = unique(B+1,B+n+1)-(B+1);
        for(int i=1;i<=n;i++) A[i] = lower_bound(B+1,B+tot+1,A[i])-B;
       //预处理r
        ll cur = 0;
	for(int i=n;i>=1;i--)
	{
	    cur += tr_r.ask(A[i]-1);   
		tr_r.add(A[i],1);	    
	} 
	int l = 1, r = 1; 
        ll ans = 0;

	while(l<n&&r<=n)
	{
		//l部分 
		cur += tr_r.ask(A[l]-1);
                cur += (tr_l.tot-tr_l.ask(A[l]));
		tr_l.add(A[l],1); 
   
		while(l==r||cur>k)
		{
			cur -= (tr_l.tot-tr_l.ask(A[r]));
			cur -= tr_r.ask(A[r]-1);
			tr_r.add(A[r],-1);
			r++;
			if(r==n+1) break;
		}
		ans += (n-r+1);
		l++;
	}
	cout<<ans;
	return 0;
}

标签:Little,int,个数,tr,tot,add,CF220E,Elephant,逆序
来源: https://www.cnblogs.com/BeautifulWater/p/15874534.html