【LOJ #6066】「2017 山东一轮集训 Day3」第二题(二分答案 / 树哈希 / 括号序列)
首先显然二分答案
其实我第一眼想得长链剖分维护树哈希
实际上由于这个子树有先后顺序
于是可以看做括号序列
每个点的子树就是若干区间
哈希判一下即可
#include<bits/stdc++.h>
using namespace std;
#define cs const
#define re register
#define pb push_back
#define pii pair<int,int>
#define ll long long
#define fi first
#define se second
#define bg begin
cs int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob)?EOF:*ib++;
}
inline int read(){
char ch=gc();
int res=0;bool f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define ull unsigned long long
template<class tp>inline void chemx(tp &a,tp b){a<b?a=b:0;}
template<class tp>inline void chemn(tp &a,tp b){a>b?a=b:0;}
cs int mod=1e9+7;
ull bas=137;
inline int add(int a,int b){return (a+=b)>=mod?(a-mod):a;}
inline int dec(int a,int b){a-=b;return a+(a>>31&mod);}
inline int mul(int a,int b){static ll r;r=1ll*a*b;return (r>=mod)?(r%mod):r;}
inline void Add(int &a,int b){(a+=b)>=mod?(a-=mod):0;}
inline void Dec(int &a,int b){a-=b,a+=a>>31&mod;}
inline void Mul(int &a,int b){static ll r;r=1ll*a*b;a=(r>=mod)?(r%mod):r;}
inline int ksm(int a,int b,int res=1){for(;b;b>>=1,Mul(a,a))(b&1)&&(Mul(res,a),1);return res;}
inline int Inv(int x){return ksm(x,mod-2);}
inline int fix(int x){return (x<0)?x+mod:x;}
cs int N=100005;
ull pw[N*2];
vector<int> e[N];
int fa[N][17],n,mxdep[N];
int in[N],id[N*2],tot,out[N];
ull has[N*2];
void dfs1(int u){
for(int i=1;i<=16;i++)fa[u][i]=fa[fa[u][i-1]][i-1];
in[u]=++tot,id[tot]=1;
mxdep[u]=0;
for(int &v:e[u]){
fa[v][0]=u,dfs1(v);
chemx(mxdep[u],mxdep[v]+1);
}
out[u]=++tot,id[tot]=mod-1;
}
map<ull,int>vis;
vector<int> p[N];
inline int jump(int u,int k){
for(int i=16;~i;i--)if(k&(1<<i))u=fa[u][i];
return u;
}
inline bool comp(int a,int b){return in[a]<in[b];}
inline ull calc(int l,int r){return has[r]-has[l-1]*pw[r-l+1];}
inline bool check(int k){
for(int i=1;i<=n;i++)
p[jump(i,k+1)].pb(i);
bool fg=0;
for(int i=1;i<=n;i++)if(mxdep[i]>=k){
sort(p[i].bg(),p[i].end(),comp);
ull res=0,l=in[i];
for(int &v:p[i]){
if(l<in[v])
res=res*pw[in[v]-l]+calc(l,in[v]-1);
l=out[v]+1;
}
res=res*pw[out[i]-l+1]+calc(l,out[i]);
if(vis.count(res)){fg=1;break;}
else vis[res]=1;
}
for(int i=1;i<=n;i++)p[i].clear();
vis.clear();
return fg;
}
int main(){
#ifdef Stargazer
freopen("lx.in","r",stdin);
#endif
n=read();
pw[0]=1;
for(int i=1;i<=2*n;i++)pw[i]=pw[i-1]*bas;
for(int i=1;i<=n;i++){
int x=read();
while(x--)e[i].pb(read());
}
dfs1(1);
for(int i=1;i<=tot;i++)has[i]=has[i-1]*bas+id[i];
int l=1,r=n,res=0;
while(l<=r){
int mid=(l+r)>>1;
if(check(mid))l=mid+1,res=mid;
else r=mid-1;
}
cout<<res<<'\n';
return 0;
}