Aizu - 2784Similarity of Subtrees(树哈希)
2017-08-26 20:14
190 查看
题意:
给你一棵树,问有多少对相似的子树(每层深度拥有相同数量的节点)。
思路:
将每棵树通过hash算法映射出一个值,下面这个公式用到了BKDRhash算法
Hash(T)= (n1+n2P+n3P2+…+nmPm−1)
% MOD /////////ni表示当前子树深度为i的节点有几个。
相当于将一棵树转化成一个p进制的整数。
代码:
给你一棵树,问有多少对相似的子树(每层深度拥有相同数量的节点)。
思路:
将每棵树通过hash算法映射出一个值,下面这个公式用到了BKDRhash算法
Hash(T)= (n1+n2P+n3P2+…+nmPm−1)
% MOD /////////ni表示当前子树深度为i的节点有几个。
相当于将一棵树转化成一个p进制的整数。
代码:
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5+7; const ll p = 137; const ll mod = 1e9+7; int n; ll Hash[maxn]; vector<int> arr[maxn]; map<ll,ll> mp; map<ll,ll>::iterator it; void dfs(int u) { Hash[u] = 1; int len = arr[u].size(); for(int i = 0;i<len;i++) { int v = arr[u][i]; dfs(v); Hash[u] = (Hash[u]+Hash[v]*p)%mod; } mp[Hash[u]]++; } int main() { scanf("%d",&n); for(int i = 0;i<n-1;i++) { int u,v; scanf("%d%d",&u,&v); arr[u].push_back(v); } dfs(1); ll ans = 0; for(it = mp.begin();it!=mp.end();it++) { ans += (it->second-1)*it->second/2; } printf("%lld\n",ans); return 0; }
相关文章推荐
- Aizu 2784 Similarity of Subtrees(树哈希)
- 【字符串哈希】【哈希表】Aizu - 1370 - Hidden Anagrams
- Aizu 2784 Similarity of Subtrees
- Aizu 1370 Hidden Anagrams 字符串哈希
- Aizu - 2784 Similarity of Subtrees(hash+dfs)
- PHP: 深入了解一致性哈希
- 【转载】哈希冲突
- 【转载】网络攻击技术(三)——Denial Of Service & 哈希相关 & PHP语言 & Java语言
- C++中的哈希容器unordered_map使用示例
- 散列表的构造和哈希冲突
- Aizu 0189 (多源 最短路Floyd )
- 算法与数据结构(十二) 散列(哈希)表的创建与查找(Swift版)
- 第十五周--用哈希组织关键字
- leetcode 49. Group Anagrams(哈希,字典序)
- redis Hash 哈希数据类型相关命令
- 字符串哈希
- 全域哈希和完全哈希
- Aizu 2306 Rabbit Party DFS
- POJ2785_4 Values whose Sum is 0_哈希||二分
- 哈希桶的实现(拉链法)