[POJ1635]Subway tree systems 判断有根树的同构 有根树哈希

诶学习了一下有根树的哈希方法
还不是很懂无根树要怎么哈希

#include <iostream>
#include <cstdio>
#include <stack>
#include <map>
#include <cstdlib>
#include <cstring>
#define N 3050
using namespace std;
typedef unsigned long long uLL;

int h[N],cnt,cur,n,tot;
uLL p[N];
char s[N];
map<uLL,uLL> mp;
stack<int> sta;
struct Edge{ int b,n; }e[2*N];
void link(int a,int b) {
//  printf("%d %d\n",a,b);
    e[++cnt].b = b, e[cnt].n = h[a], h[a] = cnt;
    e[++cnt].b = a, e[cnt].n = h[b], h[b] = cnt;
}
uLL rnd() { return (uLL)rand() * rand() * rand() * rand(); }
uLL dfs(int u,int f) {
    uLL now = 1LL;
    for (int i=h[u],v;v=e[i].b,i;i=e[i].n) {
        if (v == f) continue;
        now += p[ dfs(v,u) ];
    }
    if (mp[now]) return mp[now];
    mp[now] = ++tot;
    return tot;
}

uLL get() {
    n = strlen(s+1);
    for (int i=1;i<=cnt;i++) h[i]=0;
    cnt = 0; cur = 1;
    sta.push(1);
    for (int i=1;i<=n;i++) {
        if (s[i] == '0') {
            ++cur;
            if (!sta.empty()) link(sta.top(),cur);
            sta.push(cur);
        } else sta.pop();
    }
    return dfs(1,1);
}

int main() {
    srand(19930726);
    for (int _=0;_<N;_++) p[_] = rnd();
    int T=0; scanf("%d",&T);
    while (T--) {
        scanf("%s",s+1);
        uLL p1 = get();
        scanf("%s",s+1);
        uLL p2 = get();
        puts(p1==p2?"same":"different");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值