首页 > 技术文章 > Similarity of Subtrees

spnooyseed 2019-09-03 14:38 原文

题目描述
Define the depth of a node in a rooted tree by applying the following rules recursively:
·The depth of a root node is 0.
·The depths of child nodes whose parents are with depth d are d+1.
Let S(T,d) be the number of nodes of T with depth d. Two rooted trees T and T′ are similar if and only if S(T,d) equals S(T′,d) for all non-negative integer d.

You are given a rooted tree T with N nodes. The nodes of T are numbered from 1 to N. Node 1 is the root node of T. Let Ti be the rooted subtree of T whose root is node i. Your task is to write a program which calculates the number of pairs (i,j) such that Ti and Tj are similar and i<j.

输入
The input consists of a single test case.

N
a1 b1
a2 b2

aN−1 bN−1

The first line contains an integer N (1≤N≤100,000), which is the number of nodes in a tree. The following N−1 lines give information of branches: the i-th line of them contains ai and bi, which indicates that a node ai is a parent of a node bi. (1≤ai,bi≤N,ai≠bi) The root node is numbered by 1. It is guaranteed that a given graph is a rooted tree, i.e. there is exactly one parent for each node except the node 1, and the graph is connected.

输出
Print the number of the pairs (x,y) of the nodes such that the subtree with the root x and the subtree with the root y are similar and x<y.

样例输入
复制样例数据
5
1 2
1 3
1 4
1 5
样例输出
6
题意:输入一棵由n个点和n-1条边构成的树,求这个树中两棵相似的子树有多少对?
相似的子树:要求有相同的深度,两颗子树的节点数相同;
所以就把这个树hash一下,拥有这样代表相同子树的根节点的hash值就会相同

思路:深搜,hash表示每一个点为子树时的子树状态;
在这里插入图片描述
额 , 这个搞歪了 , 这个答案是2 , 4 和6 相似(子树深度是1 , 节点个数是1), 3 和5 相似()子树深度为2 , 节点个数为2在这里插入图片描述
第三组样例:对图上每个点,给一个标识p^d d为这个点的深度,那么每个点的子树状态就可以用子树上所有项的和表示,如2号节点p4+2p3+2p^2+p 3号节点p4+2p3+2p^2+p 它们的多项式相同,为了方便用map映射统计,可以给p赋一个值,为了减小冲突可以取一个较大的质数,这就是hash;

#include <iostream>
#include <map>
#include <cstdio>
#include <vector> 
using namespace std;
#pragma GCC optimize(3 , "Ofast" , "inline")
const int N = 1e6 + 10 , mod = 1e9 + 7 , p = 131 ;
typedef long long ll ;
vector<int> e[N] ;
ll h[N] ;
map<ll , ll> ma ;
void dfs(ll u)
{
	h[u] = 1 ;
	for(int i = 0 ;i < e[u].size() ;i ++)
	 {
	 	dfs(e[u][i]) ;
	 	h[u] = (h[u] + h[e[u][i]] * p) % mod ;
	 }
	 ma[h[u]] ++ ;
}
int main()
{
	int n ;
	scanf("%d",&n) ;
	for(int i = 1;i < n;i ++)
	 {
	 	int a , b ;
	 	scanf("%d%d",&a , &b) ;
	 	e[a].push_back(b) ;
	 }
	 dfs(1) ;
	 ll ans = 0 ;
	 map<ll , ll > ::iterator it ;
	 for(it = ma.begin() ; it != ma.end() ;it ++)
	  ans += (it->second) * (it -> second - 1) / 2 ;
     cout << ans << endl ;
}

推荐阅读