跳到正文

个人记录

树哈希

yuanzhiteng约 6 分钟
原文

这是 2026年1月14日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2023年7月21日
收录
2026年1月14日
更新
2026年11月15日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

树哈希是一种用于判断两棵树是否同构的算法。
相当于是将一棵树映射到了实数域中。
有一种不容易被 HackHack 的哈希方法:XOR SHIFTXOR\ SHIFT。
但注意,此种方法针对于 有根树。
如果是无根树,有两种方法:

  1. 由于 XOR SHIFTXOR\ SHIFT 这种方法自带 ∑\sum,故可以换根 dpdp。
  2. 我们知道,当一棵树的重心确定了,子树形态就确定了。
    所以预处理出树的重心,将重心当作根跑树哈希。
    如果有 22 个重心,将两个重心都跑一遍树哈希,然后取小的那个。

以下是代码,注意其中的数字不能随意取。
模板:树的同构(无根树的树哈希)

C++
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <random>
#include <chrono>
#include <map>
using namespace std;
typedef unsigned long long ull;
const int maxn = 105;

template <typename T>
inline void read(T& x){
x = 0; int f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -f; c = getchar(); }
while (c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); } x *= f;
}
template <typename T, typename... Args>
inline void read (T &x, Args&... Arg) { read (x), read (Arg...); }

int n,m,cnt;
int head[maxn];
struct Edge{
    int to,next;
}e[maxn << 1];
inline void add(int u,int v){
    e[++cnt].to = v;
    e[cnt].next = head[u];
    head[u] = cnt;
}
int dp[maxn],sz[maxn],root[maxn][2];
inline void dfs(int u,int fa,int id){
    sz[u] = 1;
    for(int i=head[u];i;i=e[i].next){
        int v = e[i].to;
        if(v == fa) continue;
        dfs(v,u,id);
        sz[u] += sz[v];
        dp[u] = max(dp[u],sz[v]);
    }
    dp[u] = max(dp[u],n-sz[u]);
    if(dp[u] <= n/2){
        if(!root[id][0]) root[id][0] = u;
        else root[id][1] = u;
    }
}

ull Hash[maxn][maxn];             //树哈希
ull Real_Hash[maxn];
const ull mask = std::chrono::steady_clock::now().time_since_epoch().count();
ull XOR_shift(ull x) {
    x ^= mask;
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    x ^= mask;
    return x;
}
inline void getHash(int u,int fa,int id){
    Hash[id][u] = 1;
    for(int i=head[u];i;i=e[i].next){
        int v = e[i].to;
        if(v == fa) continue;
        getHash(v,u,id);
        Hash[id][u] += XOR_shift(Hash[id][v]);
    }
}   

map<ull,int>check;
int main(){

    read(m);
    for(int i=1;i<=m;i++){
        
        memset(head,0,sizeof(head));
        memset(sz,0,sizeof(sz));
        memset(dp,0,sizeof(dp));
        cnt = 0;

        read(n);
        for(int j=1;j<=n;j++){
            int v;
            read(v);
            if(v == 0)  continue;
            add(j,v);
            add(v,j);
        }
        dfs(1,1,i);
        getHash(root[i][0],0,i);
        Real_Hash[i] = Hash[i][root[i][0]];
        if(root[i][1]){
            getHash(root[i][1],0,i);
            Real_Hash[i] = min(Hash[i][root[i][1]],Real_Hash[i]);
        }
    }
    for(int i=1;i<=m;i++){
        if(check[Real_Hash[i]]) printf("%d\n",check[Real_Hash[i]]);
        else{
            check[Real_Hash[i]] = i;
            printf("%d\n",i);
        }
    }

    return 0;
}