树的哈希,模板题。
#include<bits/stdc++.h>
#define fer(i,j,n) for(int i=j;i<=n;i++)
#define far(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
#define pa pair<int,int>
const int maxn=1010;
const int INF=1e9+7;
using namespace std;
/*----------------------------------------------------------------------------*/
inline ll read()
{
char ls;ll x=0,sng=1;
for(;ls<'0'||ls>'9';ls=getchar())if(ls=='-')sng=-1;
for(;ls>='0'&&ls<='9';ls=getchar())x=x*10+ls-'0';
return x*sng;
}
/*----------------------------------------------------------------------------*/
struct kaga
{
int next;
int point;
}e[maxn];
int m,n,ans[maxn][maxn],last[maxn],k=0,root,cnt=0;
void add_edge(int x,int y)
{
e[++k].next=y;e[k].point=last[x];last[x]=k;
}
void insert(int x,int y)
{
add_edge(x,y);
add_edge(y,x);
}
map<int,int> l[maxn];
map<vector<int>,int> h;
int dfs(int x,int fa)
{
if(l[x][fa])return l[x][fa];
vector<int> now;
for(int j=last[x];j;j=e[j].point)
{
int y=e[j].next;
if(y!=fa)now.push_back(dfs(y,x));
}
sort(now.begin(),now.end());
if(!h[now])h[now]=++cnt;
return l[x][fa]=h[now];
}
bool judge(int i,int j)
{
fer(k,1,n)
if(ans[j][k]!=ans[i][k])return false;
return true;
}
int main()
{
int m=read();
fer(i,1,m)
{
memset(last,0,sizeof(last));
k=0;
n=read();
fer(j,1,n)l[j].clear();
fer(j,1,n)
{
int x=read();
if(x)insert(x,j);
}
fer(j,1,n)
ans[i][j]=dfs(j,0);
sort(ans[i]+1,ans[i]+n+1);
fer(j,1,i)
if(judge(i,j))
{
cout<<j<<endl;
break;
}
}
}