題目
給定
分析
考慮
我使用的函數:設當前的子樹是
其中
對於每棵樹,枚舉每個節點作爲根進行dfs求出
對於求出的一個哈希值,則分 相同樹、不同樹、還沒有 這三類來更新。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <algorithm>
#include <map>
using namespace std;
#define mp(i,j) make_pair(i,j)
typedef unsigned long long ull;
typedef pair<ull,ull> pint;
const int N=64;
int m;
int n;
struct Edge
{
int v,nxt;
}mp[N<<1];
int tt,hd[N];
ull h1[2][N];
ull h2[2][N];
map<pint,int> p;
inline int rd(void)
{
int x=0; char c=getchar();
for (;!isdigit(c);c=getchar());
for (;isdigit(c);c=getchar()) x=x*10+c-'0';
return x;
}
inline int add(int u,int v)
{
mp[++tt].v=v;
mp[tt].nxt=hd[u];
hd[u]=tt;
}
ull dfs(int t,int now,int pre,int dep)
{
ull ret=h1[t][dep];
for (int k=hd[now];k;k=mp[k].nxt)
if (mp[k].v!=pre)
ret+=dfs(t,mp[k].v,now,dep+1)*h2[t][dep];
return ret*ret;
}
int main(void)
{
// freopen("c.in","r",stdin);
// freopen("c.out","w",stdout);
srand(time(0));
for (int t=0;t<=1;t++)
for (int i=1;i<N;i++)
h1[t][i]=rand(),h2[t][i]=rand();
int res; m=rd();
for (int t=1;t<=m;t++)
{
res=t;
tt=0;
memset(hd,0,sizeof hd);
int x; n=rd();
for (int i=1;i<=n;i++)
{
x=rd();
if (x) add(i,x),add(x,i);
}
ull d0,d1; pint d;
for (int rt=1;rt<=n;rt++)
{
d0=dfs(0,rt,0,1);
d1=dfs(1,rt,0,1);
d=mp(d0,d1);
if (p[d]==t) continue;
if (!p[d])
p[d]=t;
else res=min(res,p[d]);
}
printf("%d\n",res);
}
return 0;
}
更好的做法是找一個樹的固定點,然後求Hash。
我們想到了重心,但重心不唯一。
但是一棵樹如果有兩個重心,必定相鄰。
我們求出一個重心,對它和它枚舉相鄰的節點求Hash,這樣可以進行優化。
小結
關於同構問題的一些小結:
①可以用Hash或者枚舉。
②爲了提高準確率,可以考慮使用多個Hash。
③注意設計的算法要與編號無關,除非進行一次枚舉,求出
例如本題枚舉根的方法。
總之如果同構數值一定要相等。
④這種方法可以應用於所有的判斷相同整體的問題上。