P4323 [JSOI2016] 独特的树叶
这里介绍 Xor-Hash 的树哈希换根做法。
令 为设树根为 ,以 为根的子树的哈希值,有 , 是哈希函数。
令 表示以 为根整棵树的哈希值。我们先通过暴力 求出 和 。我们的目标是 求出 。
我们从 开始深搜,假设当前节点为 ,父亲为 。 的值为以 为根的树减去 这一部分的剩下部分的哈希值,加上 。用式子表达,就是 。
接着对于这道题,我们对两棵树都求出其 和 。枚举树 的每一个叶子节点 ,其父亲为 ,则删去这个叶子节点得到的哈希值应该是 。求到后判断是否有 中有某个点为根的哈希值和其相等。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <set>
using namespace std;
const int N = 1e5 + 5;
using ull = unsigned long long;
const ull P = 1930841;
int n, ff[N];
vector<int> G[N], G2[N];
ull hashing[N], hash2[N], hashing2[N], hash22[N];
set<ull> st;
ull shift(ull x)
{
x ^= P;
x ^= (x << 7);
x ^= (x >> 11);
x ^= (x << 13);
x ^= P;
return x;
}
void tree_hash1(int u, int f)
{
hashing[u] = 1;
for (int& j : G[u])
{
if (j != f)
{
tree_hash1(j, u);
hashing[u] += shift(hashing[j]);
}
}
}
void DP_HASH1(int u, int f)
{
if (u != 1) hash2[u] = shift(hash2[f] - shift(hashing[u])) + hashing[u];
for (int& j : G[u])
{
if (j != f) DP_HASH1(j, u);
}
}
void tree_hash2(int u, int f)
{
ff[u] = f;
hashing2[u] = 1;
for (int& j : G2[u])
{
if (j != f)
{
tree_hash2(j, u);
hashing2[u] += shift(hashing2[j]);
}
}
}
void DP_HASH2(int u, int f)
{
if (u != 1) hash22[u] = shift(hash22[f] - shift(hashing2[u])) + hashing2[u];
for (int& j : G2[u])
{
if (j != f) DP_HASH2(j, u);
}
}
int main()
{
scanf("%d", &n);
for (int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
G[u].emplace_back(v);
G[v].emplace_back(u);
}
for (int i = 1; i <= n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
G2[u].emplace_back(v);
G2[v].emplace_back(u);
}
tree_hash1(1, 1);
hash2[1] = hashing[1];
DP_HASH1(1, 1);
for (int i = 1; i <= n; i++)
{
st.insert(hash2[i]);
}
tree_hash2(1, 1);
hash22[1] = hashing2[1];
DP_HASH2(1, 1);
for (int i = 1; i <= n + 1; i++)
{
if (G2[i].size() == 1)
{
int fa = G2[i][0];
ull ns = hash22[fa] - shift(1);
if (st.count(ns))
{
printf("%d\n", i);
return 0;
}
}
}
return 0;
}

浙公网安备 33010602011771号