92pts求调
查看原帖
92pts求调
464732
luqyou楼主2023/5/8 16:23
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
vector<int> G[maxn];
int v[maxn],val[maxn],top[maxn],f[maxn],hson[maxn],size[maxn],dfn[maxn],rnk[maxn],depth[maxn],cnt;
int n,m,root,nxt[maxn];
string s;
void dfs1(int u,int fa,int dep){
	f[u]=fa;
	depth[u]=dep;
	size[u]=1;
	for(int i=0;i<G[u].size();i++){
		int v=G[u][i];
		if(v!=fa){
			dfs1(v,u,dep+1);
			size[u]+=size[v];
			if(size[v]>size[hson[u]]){
				hson[u]=v;
			} 
		}
	}
}
void dfs2(int u,int fa,int nowtop){
	top[u]=nowtop;
	dfn[u]=++cnt;
	rnk[cnt]=u;
	if(hson[u]){
		dfs2(hson[u],u,nowtop);
		for(int i=0;i<G[u].size();i++){
			int v=G[u][i];
			if(v!=hson[u]&&v!=fa){
				dfs2(v,u,v);
			}
		}
	}
}
int lca(int x,int y){
	int kx=x,ky=y;
	while(top[x]!=top[y]){
		int dx=depth[top[x]],dy=depth[top[y]];
		if(dx<dy){
			swap(x,y);
		}
		x=f[top[x]];
	}
	if(x==kx) x=f[x];
	if(y==ky) y=f[y];
	if(depth[x]<depth[y]) return x;
	return y;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	//size[0]=0x7fffffff;
	cin>>s;
	int len=s.size(),xx=0;
	s=" "+s;
	for(int i=2;i<=len;i++){     
		while(xx>0&&s[i]!=s[xx+1]){
	   		xx=nxt[xx];  
	   	}  
       	if(s[xx+1]==s[i]){
       		xx++; 
	   	}   
	   	nxt[i]=xx;
    }
    for(int i=1;i<=len;i++){
    	//cout<<i+1<<" "<<nxt[i]+1<<endl;
    	G[i+1].push_back(nxt[i]+1);
    	G[nxt[i]+1].push_back(i+1);
	}
	dfs1(1,1,1);
	dfs2(1,1,1);
	int m;
	cin>>m;
	for(int i=1;i<=m;i++){
		int x,y;
		cin>>x>>y;
		x++;
		y++; 
		cout<<lca(x,y)-1<<endl;
	} 
	return 0;
} 
2023/5/8 16:23
加载中...