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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现