前言
有意思。
Solution
从前往后扫描一遍颜色序列,能消除的优先消除。
考虑对上述过程每一步的栈建出操作树状物的树,不难发现只有两种操作:在末尾加入一个数,删去末尾的一个数。
也就是每扫到一个数,会向当前节点的一个子节点方向,或父亲方向移动一步。这构成了一条长为 的非简单路径。
考虑询问 ,放到操作树上考虑,从中截取 到 的非简单路径;起始状态为 对应的节点,终止状态为 对应的节点。
一个显然但重要的结论是,两次经过同一个点,其中间的所有数都可以互相消除完。
既然规定了起点终点,而两次经过同一个点中间又不重要,而且一次只能走一步。
那答案显而易见了,就是树上 和 的距离。
随便哪个 LCA 都能做, 是简单的。
Code
代码
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define infll 0x3f3f3f3f3f3f3f3fll
using namespace std;
int ufa[1000010];
static inline int find(int x){while(x!=ufa[x]) x=ufa[x]=ufa[ufa[x]];return x;}
static inline void merge(int x,int y){
x=find(x),y=find(y);
if(x==y) return;
ufa[x]=y;
}
int n,q;
int a[1000010],s[1000010];
struct queries{
int x,y,lca;
}qr[1000010];
int fa[1000010];
map<int,int> ch[1000010];
int nodecnt=0;
int newnode(){return ++nodecnt;}
vector<pair<int,int> > qrs[1000010];
int dep[1000010];
bool vis[1000010];
void dfs(int x){
dep[x]=dep[fa[x]]+1,vis[x]=true;
for(auto [val,y]:ch[x]) dfs(y),merge(y,x);
for(auto [pos,id]:qrs[x]) if(vis[pos]) qr[id].lca=find(pos);
}
int main(){
cin.tie(0)->sync_with_stdio(false);
cin>>n>>q;
for(int i=1;i<=n;i++) cin>>a[i];
s[0]=1;
stack<int> stk;
for(int i=1,p=newnode();i<=n;i++){
if(!stk.empty()&&stk.top()==a[i]) stk.pop(),p=fa[p];
else{
stk.push(a[i]);
if(!ch[p].count(a[i])) ch[p][a[i]]=newnode();
fa[ch[p][a[i]]]=p;
p=ch[p][a[i]];
}
s[i]=p;
}
for(int i=1;i<=q;i++){
int x,y;cin>>x>>y;x=s[x-1],y=s[y];
qr[i]={x,y};
qrs[x].push_back({y,i}),qrs[y].push_back({x,i});
}
for(int i=1;i<=n;i++) ufa[i]=i;
dfs(1);
for(int i=1;i<=q;i++) cout<<dep[qr[i].x]+dep[qr[i].y]-dep[qr[i].lca]*2<<"\n";
# ifdef TakanashiHoshino
cerr<<"\n\033[1;38;2;234;200;225mUsed time: "<<clock()*1.0/CLOCKS_PER_SEC<<"s.\033[0m\n";
# endif
return 0;
}