跳到正文

个人记录

Luogu P5043 【模板】树同构([BJOI2015]树的同构) 题解

xxxxxxxb约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年9月29日
收录
2025年12月31日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

模板题,树哈希 但是为什么会出现在状态设计的题单里(恼

hashu=c+∑v∈sug(hashv)mod  MODhash_u = c + \sum_{v \in s_u} g(hash_v) \mod{MOD}

这里为了好写直接自然溢出取模

直接看代码得了

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 55;
using ull = unsigned long long;
const ull mask = mt19937_64(time(0))();
int m, n, root;
ull rot[N], mhash[N];
vector<int> e[N];
map<ull, int> mp;
ull shift(ull x) { //xor shift,mask为随机常数,不重要
    x ^= mask;
    x ^= x << 13, x ^= x >> 7, x ^= x << 17;
    return x ^ mask;
}
void dfsfi(int cur) {
    mhash[cur] = 1; //换根dp第一次dfs,求出以cur的儿子们为根的哈希值的和,也就是该子树的哈希值
    for(auto v : e[cur]) {
        dfsfi(v);
        mhash[cur] += shift(mhash[v]);
    }
}
void dfsse(int cur) {
    for(auto v : e[cur]) { //第二次
                           //rot[cur]为将这棵树变换为以cur为根时的哈希值
        rot[v] = mhash[v]  + shift(rot[cur] - shift(mhash[v]));
                           //rot[v]首先就是v本身这个子树的贡献,然后就是(原来的父亲成了儿子)考虑cur为根时整棵树,不难发现变换v之后以cur为根的子树对hash贡献就是变化cur时以cur为根的树除去以v为根的子树的贡献,又考虑到这里一颗树的哈希时它的直接子树的哈希值的经过g映射之后的和,故而可以轻松地差分得到.
        dfsse(v);
    }
}
int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    cin >> m;
    for(int ith = 1; ith <= m; ++ith) {
        cin >> n;
        for(int i = 1; i <= n; ++i) {
            int pa;
            cin >> pa;
            if(pa == 0) {
                root = i;
            } else {
                e[pa].push_back(i);
            }
        }
        dfsfi(root),rot[root] = mhash[root],dfsse(root);//这里这注意一下就行
        ull mutihash = 1;
        for(int i = 1;i <= n;++i) {
            mutihash += shift(rot[i]);
        }
        if(mp.count(mutihash) == 0) {
            mp[mutihash] = ith;
        }
        cout << mp[mutihash] << '\n';
        for(int i = 1;i <= n;++i) {
            e[i].clear(); //一定要清空
        }
    }
    return 0;
}

这种方法参考于 :

oi wiki

一种好写且卡不掉的树哈希 by peehs_moorhsum

原文