本文主要是介绍树的同构(HYSBZ - 4337,树的哈希),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.题目链接:
HYSBZ-4337
二.题目大意:
输出 m 棵树的同构运算等价类.
三.分析:
貌似是个模板题...
原来这就叫做树的哈希,感觉好水啊...
详见代码.
四.代码实现:
#include <bits/stdc++.h>
using namespace std;typedef unsigned long long ull;const int M = (int)50;
const ull Base = 1331;int cnt;
struct node
{int v, nx;
}Edge[M * 2 + 5];
int head[M + 5];
int sz[M + 5];
ull Hash[M + 5][M + 5];void init()
{cnt = 0;memset(head, -1, sizeof(head));
}void add(int u, int v)
{Edge[cnt].v = v;Edge[cnt].nx = head[u];head[u] = cnt++;
}ull dfs(int u, int fa)
{sz[u] = 1;vector <ull> p;for(int i = head[u]; ~i; i = Edge[i].nx){int v = Edge[i].v;if(v == fa) continue;p.push_back(dfs(v, u));sz[u] += sz[v];}sort(p.begin(), p.end());ull ans = 0;int len = p.size();for(int i = 0; i < len; ++i)ans = ans * Base + p[i];return (ans + 1) * sz[u];
}int main()
{int m;scanf("%d", &m);for(int i = 1; i <= m; ++i){int n;scanf("%d", &n);init();int x;for(int j = 1; j <= n; ++j){scanf("%d", &x);if(x == 0) continue;add(j, x);add(x, j);}for(int j = 1; j <= n; ++j) Hash[i][j] = dfs(j, 0);sort(Hash[i] + 1, Hash[i] + n + 1);for(int j = 1; j <= i; ++j){int k = 1;while(k <= n && Hash[i][k] == Hash[j][k]) ++k;if(k == n + 1){printf("%d\n", j);break;}}}return 0;
}
这篇关于树的同构(HYSBZ - 4337,树的哈希)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!