树哈希学习笔记

树哈希

const ull T=rnd();
ull shift(ull x){
    x^=T;
    x^=x<<13;
    x^=x>>7;
    x^=x<<17;
    x^=T;
    return x;
}
ull shift(ull x){
    x^=T;
    x^=x>>12;
    x^=x<<25;
    x^=x>>27;
    x^=T;
    return x;
}

f ( S ) = ( c + ∑ x ∈ S g ( x ) ) m o d   m f(S)=(c+\sum_{x∈S} g(x))mod \ m f(S)=(c+xSg(x))mod m

c c c 一般取1即可

另外映射采用了 x o r   s h i f t xor \ shift xor shift算法

AHU算法

每个子树赋一个点值

如何赋值呢 根据其儿子的点值 push到vector里面排序

即最小表示法

最后可以利用 map<vector< int>> \text{map<vector< int>>} map<vector< int>>映射即可

当然也可以将 v e c t o r vector vector换成异或哈希的方式

洛谷P5043 【模板】树同构([BJOI2015]树的同构)

无根树 采用换根dp对所有的点作为跟求一遍哈希值 最后统计总和作为map的键即可

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define ull unsigned ll
mt19937_64 rnd(time(NULL));
vector<int>a[100020];
ull hash_v[100020];
const ull T=rnd();
map<ull,int>mp;
ull shift(ull x){
    x^=T;
    x^=x<<13;
    x^=x>>7;
    x^=x<<17;
    x^=T;
    return x;
}
void dfs(int x){
    hash_v[x]=1;
    for(auto i:a[x]){
        dfs(i);
        hash_v[x]+=shift(hash_v[i]);
    }
}
void swap_tree(int x){
    for(auto i:a[x]){
        hash_v[i]+=shift((hash_v[x]-shift(hash_v[i])));
        swap_tree(i);
    }
}
void solve(){
    int m;
    cin>>m;
    for(int k=1;k<=m;k++){
        int n;
        cin>>n;
        for(int i=1;i<=n;i++){
            int x;
            cin>>x;
            a[x].push_back(i);
        }
        dfs(a[0][0]);
        swap_tree(a[0][0]);
        ull sum=0;
        for(int i=0;i<=n;i++){
            sum+=shift(hash_v[i]);
        }
        // cout<<sum<<'\n';
        if(!mp[sum])mp[sum]=k;
        cout<<mp[sum]<<'\n';
        for(int i=0;i<=n;i++)a[i].clear();
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int t=1;
    // cin>>t;
    while(t--)solve();
    return 0;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值