Anton and Permutation(分块)

Anton and Permutation
题意:对于一个长度为 nn 的序列进行 kk 次操作,每次操作都是交换序列中的某两个数。对于每一个操作,回答当前序列中有多少个逆序对。

//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf=(int)8e18+100;
const int maxn=2e5+100;
vector<int>g[maxn];
int pos[maxn],a[maxn],sz;
int ask(int l,int r,int d)
{
	if(l>r)return 0;
	int sum=0;
	for(int i=l; i<=min(r,pos[l]*sz); i++)
	{
		if(a[i]<d)sum++;
	}
	if(pos[l]!=pos[r])
	{
		for(int i=pos[l]+1; i<=pos[r]-1; i++)
		{
			sum+=upper_bound(g[i].begin(),g[i].end(),d)-g[i].begin();
		}
		for(int i=(pos[r]-1)*sz+1; i<=r; i++)
		{
			if(a[i]<d)sum++;
		}
	}
	return sum;
}
signed main()
{
	IOS
	int n,q;
	cin>>n>>q;
	sz=sqrt(n);
	for(int i=1; i<=n; i++)
	{
		pos[i]=(i-1)/sz+1;
		a[i]=i;
		g[pos[i]].pb(i);
	}
	int ans=0;
	while(q--)
	{
		int l,r;
		cin>>l>>r;
		if(l>r)swap(l,r);
		if(l==r)
		{
			cout<<ans<<"\n";
			continue;
		}
		if(a[l]<a[r])ans++;
		else ans--;
		ans+=(ask(l+1,r-1,a[r])-ask(l+1,r-1,a[l]))*2;
		int pl=pos[l],pr=pos[r];
		if(pl!=pr)
		{
			g[pl].erase(lower_bound(g[pl].begin(),g[pl].end(),a[l]));
			g[pr].erase(lower_bound(g[pr].begin(),g[pr].end(),a[r]));
			g[pl].insert(upper_bound(g[pl].begin(),g[pl].end(),a[r]),a[r]);
			g[pr].insert(upper_bound(g[pr].begin(),g[pr].end(),a[l]),a[l]);
		}
		swap(a[l],a[r]);
		cout<<ans<<"\n";
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

thusloop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值