[BZOJ4337 BJOI2015 樹的同構]樹哈希
分類:Data Structure
Hash
template
1. 題目鏈接
2. 題意描述
Description
樹是一種很常見的數據結構。
我們把N個點,N-1條邊的連通無向圖稱爲樹。
若將某個點作爲根,從根開始遍歷,則其它的點都有一個前驅,這個樹就成爲有根樹。
對於兩個樹T1和T2,如果能夠把樹T1的所有點重新標號,使得樹T1和樹T2完全相同,那麼這兩個樹是同構的。也就是說,它們具有相同的形態。
現在,給你M個有根樹,請你把它們按同構關係分成若干個等價類。
Input
第一行,一個整數M。
接下來M行,每行包含若干個整數,表示一個樹。第一個整數N表示點數。接下來N
個整數,依次表示編號爲1到N的每個點的父親結點的編號。根節點父親結點編號爲0。
Output
輸出M行,每行一個整數,表示與每個樹同構的樹的最小編號。
數據範圍:
100% 的數據中,
3. 解題思路
樹Hash模板題。
4. 實現代碼
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lb;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ull, ull> puu;
typedef pair<lb, lb> pbb;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f;
const ll INFL = 0x3f3f3f3f3f3f3f3fLL;
const long double PI = acos(-1.0);
const long double eps = 1e-4;
template<typename T> inline void umax(T &a, T b) { a = max(a, b); }
template<typename T> inline void umin(T &a, T b) { a = min(a, b); }
void debug() { cout << endl; }
template<typename T, typename ...R> void debug (T f, R ...r) { cout << "[" << f << "]"; debug (r...); }
const int MAXN = 100;
const int MAXE = 200;
ull qz[MAXN];
struct Tree {
struct Edge {
int v, next;
} edge[MAXE];
int n, head[MAXN], tot, root;
ull h[MAXN];
void init() {
tot = 0;
memset(head, -1, sizeof(head));
}
inline void add_edge(int u, int v) {
edge[tot] = Edge{v, head[u]};
head[u] = tot ++;
}
void read() {
scanf("%d", &n);
int fa;
for (int i = 1; i <= n; ++i) {
scanf("%d", &fa);
if (fa == 0) root = i;
else {
add_edge(fa, i);
add_edge(i, fa);
}
}
}
int siz[MAXN], mx_sum, g[MAXN], g_cnt;
void dfs(int u, int fa) {
int v, temp = 0;
siz[u] = 1;
for (int i = head[u]; ~i; i = edge[i].next) {
v = edge[i].v;
if (v == fa) continue;
dfs(v, u);
siz[u] += siz[v];
umax(temp, siz[v] + 1);
}
umax(temp, n - siz[u] + 1);
if (temp < mx_sum) {
mx_sum = temp;
g_cnt = 0;
g[g_cnt ++] = u;
} else if (mx_sum == temp) {
g[g_cnt ++] = u;
}
}
void hash_dfs(int u, int fa) {
int v;
h[u] = siz[u] = 1;
for (int i = head[u]; ~i; i = edge[i].next) {
v = edge[i].v;
if (v == fa) continue;
hash_dfs(v, u);
h[u] += h[v] ^ qz[siz[v]];
siz[u] += siz[v];
}
h[u] *= qz[n - siz[u] + 1];
}
ull hashV() {
mx_sum = INF; g_cnt = 0;
dfs(root, 0);
ull hv = 1;
for(int i = 0; i < g_cnt; ++i) {
hash_dfs(g[i], 0);
hv *= h[g[i]];
}
return hv;
}
} tr;
int main() {
#ifdef ___LOCAL_WONZY___
freopen ("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
for (int i = 0; i < MAXN; ++i) qz[i] = (ull) rand() * rand();
int m;
while (~scanf("%d", &m)) {
map<ull, int> mp;
for (int i = 1; i <= m; ++i) {
tr.init();
tr.read();
ull hv = tr.hashV();
if (!mp[hv]) mp[hv] = i;
printf("%d\n", mp[hv]);
}
}
#ifdef ___LOCAL_WONZY___
cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif // ___LOCAL_WONZY___
return 0;
}