4337: BJOI2015 树的同构

时间:2021-07-26 20:58:05

题解:

树的同构的判定

有根树从根开始进行树hash

先把儿子的f进行排序

$f[i]=\sum_{j=1}^{k} { f[j]*prime[j]} +num[i]$(我没有仔细想这样是不是树是唯一的。。。反正过了)

无根树先找到重心再作为根

因为重心最多只有两个,复杂度仍旧O(n)

代码:

#include <bits/stdc++.h>
using namespace std;
#define rint register int
#define IL inline
#define rep(i,h,t) for (int i=h;i<=t;i++)
#define dep(i,t,h) for (int i=t;i>=h;i--)
#define me(x) memset(x,0,sizeof(x))
#define ll long long
#define mep(x,y) memcpy(x,y,sizeof(y))
#define mid ((h+t)>>1)
#define ull unsigned ll
namespace IO{
char ss[<<],*A=ss,*B=ss;
IL char gc()
{
return A==B&&(B=(A=ss)+fread(ss,,<<,stdin),A==B)?EOF:*A++;
}
template<class T>void read(T &x)
{
rint f=,c; while (c=gc(),c<||c>) if (c=='-') f=-; x=(c^);
while (c=gc(),c>&&c<) x=(x<<)+(x<<)+(c^); x*=f;
}
char sr[<<],z[]; int Z,C=-;
template<class T>void wer(T x)
{
if (x<) sr[++C]='-',x=-x;
while (z[++Z]=x%+,x/=);
while (sr[++C]=z[Z],--Z);
}
IL void wer1() { sr[++C]=' ';}
IL void wer2() { sr[++C]='\n';}
template<class T>IL void maxa(T &x,T y) { if (x<y) x=y;}
template<class T>IL void mina(T &x,T y) { if (x>y) x=y;}
template<class T>IL T MAX(T x,T y) {return x>y?x:y;}
template<class T>IL T MIN(T x,T y) {return x<y?x:y;}
};
using namespace IO;
const int N=;
int head[N],n,m,l,num[N],f[N];
struct re{
int a,b;
}e[N*];
bool q[];
int zs[N];
ull son[N][N],ans[N],g[N];
IL void arr(int x,int y)
{
e[++l].a=head[x];
e[l].b=y;
head[x]=l;
}
void fdrt(int x,int y)
{
num[x]=;
for (rint u=head[x];u;u=e[u].a)
{
int v=e[u].b;
if (v!=y)
{
fdrt(v,x);
num[x]+=num[v];
if (num[v]>f[x]) f[x]=num[v];
}
}
if (n-num[x]>f[x]) f[x]=n-num[x];
}
void dfs(int x,int y)
{
num[x]=;
int cnt=;
for (rint u=head[x];u;u=e[u].a)
{
int v=e[u].b;
if (v!=y)
{
dfs(v,x);
son[x][++cnt]=g[v];
num[x]+=num[v];
}
}
sort(son[x]+,son[x]+cnt+);
ull now=;
rep(i,,cnt) now=now+son[x][i]*zs[i];
now+=num[x];
g[x]=now;
}
int main()
{
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
read(m);
rep(i,,)
for (int j=;j*i<=;j++)
q[i*j]=;
int cnt=;
rep(i,,)
if (!q[i])
{
zs[++cnt]=i;
if (cnt>=) break;
}
rep(j,,m)
{
me(head); read(n); me(f); l=;
rep(i,,n)
{
int x,y; read(x);
if (x) arr(x,i),arr(i,x);
}
fdrt(,);
int ma=1e9;
rep(i,,n) ma=min(ma,f[i]);
rep(i,,n)
if (f[i]==ma)
{
dfs(i,); maxa(ans[j],g[i]);
}
}
rep(i,,m)
rep(j,,m)
if(ans[j]==ans[i])
{
cout<<j<<endl; break;
}
return ;
}