哈希
树哈希,就是对于树的哈希
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
int m,n;
vector<int> son[60];
ull shift(ull x){
x^=x<<13;
x^=x>>7;
x^=x<<17;
return x;
}
ull f[60],g[60];
void dfs1(int x){
f[x]=1;
for(auto y:son[x]){
dfs1(y);
f[x]+=shift(f[y]);
}
}
void dfs2(int x){
for(auto y:son[x]){
g[y]=f[y]+shift(g[x]-shift(f[y]));//notice the double shift
dfs2(y);
}
}
ull a[60];
int ans[60];
struct Hash_Table{
int M;
vector<pair<ull,int>> a[2000010];
Hash_Table(){
M=1000003;
}
int Hash(ull x){
return x%M;
}
void insert(ull val,int id){
int h=Hash(val);
for(int i=0;i<a[h].size();++i)
if(a[h][i].first==val){
ans[id]=a[h][i].second;
return;
}
ans[id]=id;
a[h].emplace_back(val,id);
}
}H;
int main(){
cin>>m;
for(int i=1;i<=m;++i){
cin>>n;int rt;
for(int i=1;i<=n;++i)son[i].clear();
for(int i=1;i<=n;++i){
int p;cin>>p;
if(p==0)rt=i;
else son[p].emplace_back(i);
}
dfs1(rt);
g[rt]=f[rt];
dfs2(rt);
ull res=1;
for(int j=1;j<=n;++j)res+=shift(g[j]);
H.insert(res,i);
printf("%d\n",ans[i]);
}
return 0;
}
标签:rt,Hash,哈希,int,son,ull
From: https://www.cnblogs.com/life-of-a-libertine/p/18038790