CF718D Andrew and Chemistry 题解
一道树哈希模板题。
由于度数很小,我们考虑直接搜索。
使用记搜,如果当前节点已经访问过就直接返回原来的值。
至于哈希的过程,我们考虑用 \(\text{vector}\) 来存储。
每个 \(\text{vector}\) 所存储的都是其儿子的哈希值,就可以不断递归向上合并。
为了减少常数,可以不选 \(\text{map}\) 采用 \(\text{pbds}\) 中 \(O(1)\) 的 \(\text{hash table}\)
Code
#include
#include
using namespace std;
using namespace __gnu_pbds;
const int maxn = 100010;
int n , cnt , tot , du[maxn] , head[maxn];
set q;
map , int> Hash;
gp_hash_table mp[maxn];
struct edge
{
int to , nxt;
}e[maxn * 2];
inline int read()
{
int asd = 0 , qwe = 1; char zxc;
while(!isdigit(zxc = getchar())) if(zxc == '-') qwe = -1;
while(isdigit(zxc)) asd = asd * 10 + zxc - '0' , zxc = getchar();
return asd * qwe;
}
inline void add(int x , int y)
{
du[x]++ , du[y]++;
e[++cnt] = {y , head[x]} , head[x] = cnt;
e[++cnt] = {x , head[y]} , head[y] = cnt;
}
inline int dfs(int now , int fa)
{
if(mp[now][fa]) return mp[now][fa];
vector tmp;
for(int i = head[now];i;i = e[i].nxt)
{
if(e[i].to == fa) continue;
tmp.push_back(dfs(e[i].to , now));
}
sort(tmp.begin() , tmp.end());
if(!Hash[tmp]) Hash[tmp] = ++tot;
return mp[now][fa] = Hash[tmp];
}
int main()
{
n = read();
for(int i = 1;i < n;i++)
{
int x = read() , y = read();
add(x , y);
}
for(int i = 1;i <= n;i++) if(du[i] < 4) q.insert(dfs(i , 0));
cout << q.size();
return 0;
}