【bzoj4337】【BJOI2015】【树的同构】【hash】

Description

树是一种很常见的数据结构。
我们把N个点,N-1条边的连通无向图称为树。
若将某个点作为根,从根开始遍历,则其它的点都有一个前驱,这个树就成为有根树。
对于两个树T1和T2,如果能够把树T1的所有点重新标号,使得树T1和树T2完全相
同,那么这两个树是同构的。也就是说,它们具有相同的形态。
现在,给你M个有根树,请你把它们按同构关系分成若干个等价类。

Input

第一行,一个整数M。
接下来M行,每行包含若干个整数,表示一个树。第一个整数N表示点数。接下来N
个整数,依次表示编号为1到N的每个点的父亲结点的编号。根节点父亲结点编号为0。

Output

输出M行,每行一个整数,表示与每个树同构的树的最小编号。

Sample Input

4
4 0 1 1 2
4 2 0 2 3
4 0 1 1 1
4 0 1 2 3

Sample Output

1
1
3
1

HINT

【样例解释】 

编号为1, 2, 4 的树是同构的。编号为3 的树只与它自身同构。 

100% 的数据中,1 ≤ N, M ≤ 50。 

题解:

         从每个点开始将这棵树hash一遍然后判断即可.

         我采用的hash方法是

            hash[x]=sigma(hash[st[i]]*p[i+1])+p[1] st[i]代表x的第i棵子树,p是一个素数表.

         注意这些子树需要按hash值排序.

代码:

         

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define N 110
#define M 3000
#define ui unsigned int
using namespace std;
int n,m,x,point[N],next[M<<1],cnt;
unsigned int hash[N][N],f[N];
unsigned int p[]={0,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};
struct use{
  int st,en;
}e[M<<1];
int read(){
  int x(0);char ch=getchar();
  while (ch<'0'||ch>'9') ch=getchar();
  while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
  return x; 
}
void add(int x,int y){
  next[++cnt]=point[x];point[x]=cnt;
  e[cnt].st=x;e[cnt].en=y;
}
void dfs(int x,int fa){
  int top=0;
  unsigned int st[N];
  st[++top]=1;
  for (int i=point[x];i;i=next[i])
    if (e[i].en!=fa){
      dfs(e[i].en,x);
      st[++top]=f[e[i].en];
    }
  sort(st+1,st+top+1);
  f[x]=0;
  for (int i=1;i<=top;i++) f[x]+=st[i]*p[i]; 
}
int main(){
  //freopen("a.in","r",stdin);
  m=read();
  for (int i=1;i<=m;i++){
    n=read();
    memset(point,0,sizeof(point));
    for (int j=1;j<=n;j++){
      x=read();
      if (x) add(x,j),add(j,x);
    }
    for (int j=1;j<=n;j++){
      dfs(j,0);
      hash[i][j]=f[j];
     // cout<<j<<' '<<f[j]<<endl;
    }
    sort(hash[i]+1,hash[i]+n+1);
    //for (int j=1;j<=n;j++) cout<<hash[i][j]<<' ';
    //cout<<endl;
    for (int j=1;j<=i;j++){
      int k;
      for (k=1;k<=n;k++)
        if (hash[j][k]!=hash[i][k]) break;
      if (k>n) {printf("%d\n",j);break;}
    }
  } 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值