P4323 [JSOI2016]獨特的樹葉(樹雜湊)
阿新 • • 發佈:2018-12-09
樹雜湊?->這裡
反正大概就是亂搞……的吧……
//minamoto #include<bits/stdc++.h> #define R register #define ll long long #define fp(i,a,b) for(R int i=a,I=b+1;i<I;++i) #define fd(i,a,b) for(R int i=a,I=b-1;i>I;--i) #define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v) template<class T>inline bool cmin(T&a,const T&b){return a>b?a=b,1:0;} template<class T>inline bool cmax(T&a,const T&b){return a<b?a=b,1:0;} using namespace std; char buf[1<<21],*p1=buf,*p2=buf; inline char getc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;} int read(){ R int res,f=1;R char ch; while((ch=getc())>'9'||ch<'0')(ch=='-')&&(f=-1); for(res=ch-'0';(ch=getc())>='0'&&ch<='9';res=res*10+ch-'0'); return res*f; } const int N=1e5+5,Base=998244353,P=1e9+7; struct eg{int v,nx;}e[N<<1];int head[N],tot;bool is; int n,m,f[N],fa[N],g[N],bin[N],sz[N],deg[N],ans=P,u,v; vector<int>son[N],sl[N],sr[N];set<int>vis; inline void add(R int u,R int v){if(is)++deg[v];e[++tot]={v,head[u]},head[u]=tot;} int dfs1(int u,int fat){ sz[u]=1,fa[u]=fat,vector<int>().swap(son[u]); go(u)if(v!=fat)son[u].push_back(dfs1(v,u)),sz[u]+=sz[v]; if(son[u].empty())return f[u]=1;sort(son[u].begin(),son[u].end()); ll res=0;fp(i,0,son[u].size()-1)res=(res*Base+son[u][i])%P; return f[u]=sz[u]*res%P; } void dfs2(int u){ if(fa[u])son[u].push_back(g[u]),sort(son[u].begin(),son[u].end()); int Sz=son[u].size();sl[u].resize(Sz),sl[u][0]=son[u][0]; fp(i,1,Sz-1)sl[u][i]=(1ll*sl[u][i-1]*Base+son[u][i])%P; sr[u].resize(Sz),sr[u][Sz-1]=son[u][Sz-1]; fd(i,Sz-2,0)sr[u][i]=(sr[u][i+1]+1ll*son[u][i]*bin[Sz-i-1])%P; go(u)if(v!=fa[u]){ if(Sz==1){g[v]=1,dfs2(v);break;} int p=lower_bound(son[u].begin(),son[u].end(),f[v])-son[u].begin(); g[v]=0;if(p+1<Sz)g[v]=sr[u][p+1]; if(p-1>=0)g[v]=(g[v]+1ll*sl[u][p-1]*bin[Sz-1-p])%P; g[v]=1ll*g[v]*(n-sz[v])%P; if(is&°[v]==1&&vis.find(g[v])!=vis.end())cmin(ans,v); dfs2(v); }if(!is)vis.insert(1ll*sl[u][Sz-1]*n%P); } int main(){ // freopen("testdata.in","r",stdin); bin[0]=1;fp(i,1,N-1)bin[i]=1ll*bin[i-1]*Base%P; n=read();fp(i,1,n-1)u=read(),v=read(),add(u,v),add(v,u); dfs1(1,0),dfs2(1),tot=0,is=1,++n;memset(head,0,sizeof(head)); fp(i,1,n-1)u=read(),v=read(),add(u,v),add(v,u); dfs1(1,0);if(deg[1]==1&&vis.find(f[e[head[1]].v])!=vis.end())ans=1; else dfs2(1);printf("%d\n",ans);return 0; }