题意:给出n棵树,问有哪些树是同构的。
注意到树很多,直接像普通的树hash是行不通的,因为哪怕是自然溢出做模数的冲突概率也极大,正确的做法是对于不同的子树使用不同的base去做hash,就可以将冲突的概率降到最低。
#include<cstdio>
#include<algorithm>
#include<cstring>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=1e5+5;
typedef unsigned long long ull;
ull hash[505][505],g[N];
int head[N],next[N],go[N];
ull p[]={0,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317};
int tot,n,m;
inline void add(int x,int y)
{
go[++tot]=y;next[tot]=head[x];head[x]=tot;
go[++tot]=x;next[tot]=head[y];head[y]=tot;
}
inline void dfs(int x,int fa)
{
ull tmp[55];int cnt=0;tmp[++cnt]=1;
for(int i=head[x];i;i=next[i])
{
int v=go[i];
if (v!=fa)
{
dfs(v,x);
tmp[++cnt]=g[v];
}
}
sort(tmp+1,tmp+1+cnt);
g[x]=0;
fo(i,1,cnt)
g[x]+=tmp[i]*p[i];
}
int main()
{
scanf("%d",&m);
fo(i,1,m)
{
scanf("%d",&n);
memset(head,0,sizeof(head));tot=0;
fo(j,1,n)
{
int x;
scanf("%d",&x);
if (x)add(j,x);
}
fo(j,1,n)
{
dfs(j,0);
hash[i][j]=g[j];
}
sort(hash[i]+1,hash[i]+n+1);
fo(j,1,i)
{
bool flag=0;
fo(k,1,n)
if (hash[j][k]!=hash[i][k])
{
flag=1;
break;
}
if (!flag)
{
printf("%d\n",j);
break;
}
}
}
}