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         else t=0;//这里没加wa了一次
17     }
18     else
19     {
20         if(!ma.count({ls,rs}))ma[{ls,rs}]=++tot;
21         num[t=ma[{ls,rs}]]++;
22     }
23     return t;
24 }
25 int main()
26 {
27     int t,n,m;
28     scanf("%d",&t);
29     while(t--)
30     {
31         ma.clear();
32         scanf("%d%d",&n,&m);
33         for(int i=1;i<=n;i++)num[i]=0;
34         for(int i=1;i<=n;i++)scanf("%d%d",&a[0][i],&a[1][i]);
35         tot=0;f=0;dfs(1);
36         for(int i=1;i<=m;i++)scanf("%d%d",&a[0][i],&a[1][i]);
37         ans=0;f=1;dfs(1);
38         printf("%lld\n",ans);
39     }
40     return 0;
41 }

posted on 2019-10-11 09:46  大桃桃  阅读(176)  评论(0编辑  收藏  举报

导航