题解:CF2147F Exchange Queries
画图!
做法
记两个排列为
把
对于每个物品,它能换到的所有物品都可以表示成
然后暴力做法就是每次找当前能换到的物品中是否有能扩展的,如果有的话就扩展,直到不能扩展为止。
那么我们研究终止状态长什么样。
如果当前状态的标红的两个区域有点的话,那么就可以扩展。所以终止状态一定是这两个区域没有点的。
有一个结论:终止状态的顶点一定在直线
在解决怎么维护终止状态之前,先来解决假设我们已经知道了终止状态的序列,怎么算答案。
一个点会跳到它的后继终止状态(也就是可达的点包含它的最小的那个),这是因为首先可达的点不包含它的肯定不行,然后它肯定能跳到这个后继,而且跳到这个后继之后就出不去了。
然后终止状态
上面的过程严谨的说就是:设
下面考虑怎么维护终止状态。我们反过来,从一个点
我们维护
代码
#include<bits/stdc++.h>
#define int long long
#define ll long long
#define ull unsigned long long
#define pii pair<ll,ll>
#define fi first
#define se second
#define i128 __int128
#define ALL(x) x.begin(),x.end()
#define popcount(x) __builtin_popcountll(x)
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
using namespace std;
const ll INF=1e18;
const int N=100005;
const int MOD1=1e9+7,MOD2=998244353;
const int MOD=MOD1;
int n,m;
int p[N],q[N];
struct segtree{
struct node{
int mn;
int res;
//res是后继到当前区间开头的距离总和
int cnt;//当前节点后面有几个没有区间min的
//没有区间min的先不算
int pos;//第一个区间min到开头的距离
int len;
node operator + (node y){
node t;
t.len=len+y.len;
if(mn==y.mn){
t.mn=mn;
t.cnt=y.cnt;
t.pos=pos;
t.res=res+y.res+(y.len-y.cnt)*len+cnt*(y.pos+len+1);
}else if(mn<y.mn){
t.mn=mn;
t.cnt=cnt+y.len;
t.res=res;
t.pos=pos;
}else{
t.mn=y.mn;
t.pos=len+y.pos;
t.cnt=y.cnt;
t.res=y.res+(y.len-y.cnt)*len+len*(y.pos+len+1);
}
return t;
}
}tr[4*N];
int tag[4*N];
void pushdown(int p){
if(tag[p]){
tr[p*2].mn+=tag[p];
tr[p*2+1].mn+=tag[p];
tag[p*2]+=tag[p];
tag[p*2+1]+=tag[p];
tag[p]=0;
}
}
void pushup(int p){
tr[p]=tr[p*2]+tr[p*2+1];
}
void build(int p,int l,int r){
tag[p]=0;
if(l==r){
tr[p].mn=0;
tr[p].len=1;
tr[p].cnt=tr[p].pos=0;
tr[p].res=1;
return;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
pushup(p);
}
void modify(int p,int l,int r,int L,int R,int x){
if(L>R)return;
if(l>=L&&r<=R){
tr[p].mn+=x;
tag[p]+=x;
return;
}
pushdown(p);
int mid=(l+r)/2;
if(mid>=L)modify(p*2,l,mid,L,R,x);
if(mid<R)modify(p*2+1,mid+1,r,L,R,x);
pushup(p);
}
}T;
void del(int i){
int l=min(p[i],q[i]),r=max(p[i],q[i]);
T.modify(1,1,n,l,r-1,-1);
}
void add(int i){
int l=min(p[i],q[i]),r=max(p[i],q[i]);
T.modify(1,1,n,l,r-1,1);
}
void solve_(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>p[i];
}
for(int i=1;i<=n;i++){
cin>>q[i];
}
T.build(1,1,n);
for(int i=1;i<=n;i++){
add(i);
}
for(int i=1;i<=m;i++){
int op,x,y;
cin>>op>>x>>y;
if(op==1){
del(x);
del(y);
swap(p[x],p[y]);
//(p[x],q[x]) (p[y],q[y]) -> (p[y],q[x]) (p[x],q[y])
add(x);
add(y);
}else{
del(x);
del(y);
swap(q[x],q[y]);
add(x);
add(y);
}
cout<<T.tr[1].res<<"\n";
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int testcase,multitest=1;
if(multitest)cin>>testcase;
else testcase=1;
while(testcase--){
solve_();
}
return 0;
}