【树哈希】BZOJ4337 BJOI2015 树的同构

题面在这里

这题树哈希就好了

我的哈希函数是:

hashi=p0+hashsonj×pj

其中 sonj 是i的第j个儿子, pj 是一个素数表

注意儿子需要按哈希值排序

注意题目说给出的是有根树是骗人的!!!

还是要枚举根处理

示例程序:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define cl(x,y) memset(x,y,sizeof(x))
using namespace std;
typedef unsigned long long ull;
inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int red(){
    int res=0,f=1;char ch=nc();
    while (ch<'0'||'9'<ch) {if (ch=='-') f=-f;ch=nc();}
    while ('0'<=ch&&ch<='9') res=res*10+ch-48,ch=nc();
    return res*f;
}

const int maxn=55,maxe=105;
const ull p[55]={51,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317};
int N,n[maxn],id[maxn];
int tot,son[maxe],lnk[maxn],nxt[maxe];
inline void add(int x,int y){
    son[++tot]=y;nxt[tot]=lnk[x];lnk[x]=tot;
}
ull hash[maxn],table[maxn][maxn];
bool cmp(int i,int j){
    return hash[i]<hash[j];
}
void dfs(int x,int fa){
    hash[x]=p[0];
    for (int j=lnk[x];j;j=nxt[j])
     if (son[j]!=fa) dfs(son[j],x);
    id[0]=0;
    for (int j=lnk[x];j;j=nxt[j])
     if (son[j]!=fa) id[++id[0]]=son[j];
    sort(id+1,id+1+id[0],cmp);
    for (int i=1;i<=id[0];i++) hash[x]+=hash[id[i]]*p[i];
}
int main(){
    N=red();
    for (int i=1;i<=N;i++){
        n[i]=red();cl(lnk,0);tot=0;
        for (int j=1;j<=n[i];j++){
            int fa=red();
            if (fa!=0) add(fa,j),add(j,fa);
        }
        for (int j=1;j<=n[i];j++)
         dfs(j,0),table[i][j]=hash[j];
        sort(table[i]+1,table[i]+1+n[i]);
    }
    for (int i=1;i<=N;i++){
        for (int j=1;j<=N;j++)
        if (n[i]==n[j]){
            int suc=1;
            for (int k=1;k<=n[i];k++)
             if (table[i][k]!=table[j][k]) {suc=0;break;}
            if (suc) {printf("%d\n",j);break;}
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值