【链接】
bzoj4337
【题目大意】
给出 m 个无根树但好像题目说是有根树,好坑QAQ,求每棵树的同构的最小编号。
【解题报告】
判断树的同构,直接Hash大法,Hash大法妙啊。
#include
#include
#include
using namespace std;
typedef unsigned long long ULL;
const int maxn=55,maxm=105,Ha=2333;
const int p[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,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};
int m,tot,n[maxn],lnk[maxn],son[maxm],nxt[maxm];
ULL ha[maxn][maxn];
inline char nc()
{
static char buf[100000],*l,*r;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
inline int Read()
{
int res=0; char ch=nc();
while (ch<'0'||ch>'9') ch=nc();
while (ch>='0'&&ch<='9') res=res*10+ch-48,ch=nc();
return res;
}
void Add(int x,int y) {son[++tot]=y; nxt[tot]=lnk[x]; lnk[x]=tot;}
int Dfs(int x,int fa)
{
int num=0; ULL now[maxn],v=Ha;
for (int j=lnk[x]; j; j=nxt[j])
if (son[j]!=fa) now[++num]=Dfs(son[j],x);
sort(now+1,now+1+num); for (int i=1; i<=num; i++) v=v*Ha+now[i]*p[i]; return v;
}
int main()
{
freopen("4337.in","r",stdin);
freopen("4337.out","w",stdout);
m=Read();
for (int i=1; i<=m; i++)
{
n[i]=Read(); tot=0;
memset(lnk,0,sizeof(lnk));
for (int j=1,x; j<=n[i]; j++) {x=Read(); if (x) Add(j,x),Add(x,j);}
for (int j=1; j<=n[i]; j++) ha[i][j]=Dfs(j,0); sort(ha[i]+1,ha[i]+1+n[i]);
for (int j=1,k; j<=i; j++)
if (n[i]==n[j])
{
for (k=1; k<=n[i]; k++)
if (ha[i][k]!=ha[j][k]) break;
if (k>n[i]) {printf("%d\n",j); break;}
}
}
return 0;
}