TZOJ 4292 Count the Trees(树hash)
作者:互联网
描述
A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T. Two binary trees are called identical if their left subtrees are the same(or both having no left subtree) and their right subtrees are the same(or both having no right subtrees).
According to a recent research, some people in the world are interested in counting the number of identical subtree pairs, each from the given trees respectively.
Now, you are given two trees. Write a program to help to count the number of identical subtree pairs, such that the first one comes from the first tree and the second one comes from the second tree.
输入
There are multiple test cases. The first line contains a positive integer T (T ≤ 20) indicating the number of test cases. Then T test cases follow.
In each test case, There are two integers n and m (1 ≤ n, m ≤ 100000) indicating the number of nodes in the given two trees. The following n lines describe the first tree. The i-th line contains two integers u and v (1 ≤ u ≤ n or u = -1, 1 ≤ v ≤ n or v = -1) indicating the indices of the left and right children of node i. If u or v equals to -1, it means that node i don't have the corresponding left or right child. Then followed by m lines describing the second tree in the same format. The roots of both trees are node 1.
输出
For each test case, print a line containing the result.
样例输入
2
2 2
-1 2
-1 -1
2 -1
-1 -1
5 5
2 3
4 5
-1 -1
-1 -1
-1 -1
2 3
4 5
-1 -1
-1 -1
-1 -1
样例输出
1
11
提示
The two trees in the first sample look like this.
题意
给你两棵二叉树,问有多少颗子树完全相同。
题解
树hash,一颗二叉子树的hash值等于pair(左儿子,右儿子)的hash值。
那么进行两遍dfs,第一遍统计hash值,第二遍计算。
代码
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 const int N=1e5+5; 5 ll ans; 6 int a[2][N],num[N],tot,f; 7 map< pair<int,int>,int >ma; 8 int dfs(int u) 9 { 10 int ls=-1,rs=-1,t; 11 if(a[0][u]!=-1)ls=dfs(a[0][u]); 12 if(a[1][u]!=-1)rs=dfs(a[1][u]); 13 if(f) 14 { 15 if(ma.count({ls,rs}))ans+=num[t=ma[{ls,rs}]]; 16 } 17 else 18 { 19 if(!ma.count({ls,rs}))ma[{ls,rs}]=++tot; 20 num[t=ma[{ls,rs}]]++; 21 } 22 return t; 23 } 24 int main() 25 { 26 int t,n,m; 27 scanf("%d",&t); 28 while(t--) 29 { 30 scanf("%d%d",&n,&m); 31 for(int i=1;i<=n;i++)num[i]=0; 32 for(int i=1;i<=n;i++)scanf("%d%d",&a[0][i],&a[1][i]); 33 tot=0;f=0;dfs(1); 34 for(int i=1;i<=m;i++)scanf("%d%d",&a[0][i],&a[1][i]); 35 ans=0;f=1;dfs(1);ma.clear(); 36 printf("%lld\n",ans); 37 } 38 return 0; 39 }
标签:Count,hash,rs,int,ma,tree,trees,ls,TZOJ 来源: https://www.cnblogs.com/taozi1115402474/p/11652192.html