luogu P5043

Topic Link

The meaning of problems

To m (m <= 50) trees, each tree node <= 50, and Q each tree isomorphic minimum number which is a tree, each tree is the order number of the input.

solution

Tree hash: dfs while to compute a hash value for each node, and then finally there will be a hash value of the root node, since this hash and choose which point to the root of a great relationship, so you need every point, run as root side, and then obtain the hash array for each node as the root of a tree, whether two trees to isomorphic comparison also needs to be a row of the array sequence, corresponding to a minimum notation, this can be directly compared.

note

First of all, it should be for dfs each node needs to open an array son hash value of the record, I started using a global array of records, there have been mixed, WA fly.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=998244353,step=2333;
const int maxn=55;
inline int read(){
	char c=getchar();int t=0,f=1;
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){t=(t<<3)+(t<<1)+(c^48);c=getchar();}
	return t*f;
}
int m,n,rt;
struct edge{
	int v,p;
}e[maxn<<1];
int h[maxn],cnt;
inline void add(int a,int b){
	e[++cnt].p=h[a];
	e[cnt].v=b;
	h[a]=cnt;
	e[++cnt].p=h[b];
	e[cnt].v=a;
	h[b]=cnt;
}
ll alfa[maxn],pos[maxn][maxn];
int dep[maxn];
void dfs(int u,int fa){
	int tot=0;
	ll ton[maxn];
	for(int i=h[u];i;i=e[i].p){
		int v=e[i].v;
		if(v==fa)continue;
		dfs(v,u);
		ton[++tot]=alfa[v];//printf("%d %d %lld\n",u,v,alfa[v]);
	}
	sort(ton+1,ton+1+tot);
	//for(int i=1;i<=tot;i++)printf("%lld ",ton[i]);
	//puts("");
	alfa[u]=1;
	for(int i=1;i<=tot;i++){
		alfa[u]=(alfa[u]*step%mod+ton[i])%mod;
	}
	alfa[u]=alfa[u]*step%mod;
}
int main(){
	//freopen("5043.in","r",stdin);
	//freopen("5043.out","w",stdout);
	m=read();
	for(int i=1;i<=m;i++){
		memset(e,0,sizeof(e));cnt=0;
		memset(h,0,sizeof(h));
		int n=read();
		for(int j=1;j<=n;j++){
			int x=read();
			if(x!=0){
				add(x,j);
			}
		}
		for(int j=1;j<=n;j++){memset(alfa,0,sizeof(alfa));
			dfs(j,0);
		//	printf("%d %d %lld\n",i,j,alfa[j]);
			pos[i][j]=alfa[j];
		}
		sort(pos[i]+1,pos[i]+1+n);
		/*for(int j=1;j<=n;j++){
			printf("%lld ",pos[i][j]);
		}
		puts("");*/
		for(int j=1,k=0;j<=i;j++,k=0){
			while(k<=n){if(pos[i][++k]!=pos[j][k])break;}
			if(k>n){printf("%d\n",j);break;}
		}
//		memset(dep,0,sizeof(dep));
	}
	return 0;
}

Published 62 original articles · won praise 1 · views 993

Guess you like

Origin blog.csdn.net/wmhtxdy/article/details/103856303