树的同构 poj 1635
2016-07-24 11:55
423 查看
链接
http://poj.org/problem?id=1635题意
判断两个有根树是否同构。解析
判断两个有根树是否同构,本质上是hash应用,每个点的权值是这个子树的权值和。树上某一组合不同都会导致最终结构的不同。代码
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <iostream> #include <map> #include <queue> using namespace std; const int maxn = 3000+10; typedef long long LL; vector<int>G1[maxn]; vector<int>G2[maxn]; int p1[maxn], p2[maxn]; struct hash{ int length; LL value; hash():length(0), value(0){} hash(char c):length(1), value(c){} hash(int l, LL v):length(l), value(v){} bool operator < (const hash &a) const { return value<a.value; } }; const LL magic = 321; LL pow(LL a, int b){ LL res = 1; while (b) { if (b & 1) res *= a; a *= a; b>>=1; } return res; } hash operator + (const hash &a, const hash &b) { return hash(a.length+b.length, a.value*pow(magic, b.length)+b.value); } void operator += (hash &a, const hash &b){ a = a+b; } vector<hash>child[maxn]; hash dfs(int pre, int cur, vector<int>G[maxn]) { hash ret; child[cur].clear(); for (int i=0; i<G[cur].size(); i++) { if (G[cur][i] == pre) continue; child[cur].push_back(dfs(cur, G[cur][i], G)); } sort(child[cur].begin(), child[cur].end()); for (int i=0; i<child[cur].size(); i++) ret += child[cur][i]; ret = '(' + ret + ')'; return ret; } LL gethash(int root, vector<int>m[maxn]) { return dfs(-1, root, m).value; } int main() { int T; scanf("%d", &T); while (T--) { char s[maxn]; scanf("%s", s); int slen = strlen(s); int t=0; int now = 0; for (int i=0; i<slen; i++) G1[i].clear(), G2[i].clear(); for (int i=0; i<slen; i++) { if (s[i] == '1') now = p1[now]; else { t++; G1[now].push_back(t); p1[t] = now; now = t; } } char p[maxn]; scanf("%s", p); int plen = strlen(p); t = 0; now = 0; for (int i=0; i<plen; i++) { if (p[i] == '1') now = p2[now]; else { t++; G2[now].push_back(t); p2[t] = now; now = t; } } if (slen != plen) { puts("differrent"); continue; } LL tree1 = gethash(0, G1); LL tree2 = gethash(0, G2); if (tree1 == tree2) puts("same"); else puts("different"); } return 0; }
相关文章推荐
- c语言实现hashmap(转载)
- Ruby中Hash的11个问题解答
- Ruby简明教程之数组和Hash介绍
- 在C#中生成与PHP一样的MD5 Hash Code的方法
- js中hash和ico的关联分析
- 详解JavaScript中Hash Map映射结构的实现
- Javascript SHA-1:Secure Hash Algorithm
- 理解php Hash函数,增强密码安全
- Ruby中Hash哈希结构的基本操作方法小结
- PHP利用hash冲突漏洞进行DDoS攻击的方法分析
- PowerShell中定义哈希散列(Hash)和调用例子
- Redis String 类型和 Hash 类型学习笔记与总结
- php操作redis中的hash和zset类型数据的方法和代码例子
- Perl 哈希Hash用法之入门教程
- perl哈希hash的常见用法介绍
- php自定义hash函数实例
- php对文件进行hash运算的方法
- php常用hash加密函数
- PHP Hash算法:Times33算法代码实例
- php的hash算法介绍