樹哈希。

· · 算法·理论

「命運敲定了要這麼發生」

忘記 AHU 了,其實是一開始就沒學懂,所以來幹樹哈希。

其實樹哈希這個東西應該沒啥能說的,感覺就是把字符串哈希扔到了樹上。

應該是看看板子題代碼就能理解了吧。。。

#include <bits/stdc++.h>

using namespace std;
using ull = unsigned long long;

const int N = 1e6 + 3;
const ull MOD = 100000780991, mask = mt19937_64 (time (0)) ();

int n;
ull f[N];

set<ull> ans;
vector<int> g[N];

ull Calc (ull x) {
  x ^= mask;
  x ^= 78ll * x ^ 91ll * x;
  x ^= x << 13ll;
  x ^= x >> 13ll;
  x ^= mask;
  return x;
}

void dfs (int x, int fa) {
  f[x] = 1;
  for (auto to : g[x]) {
    if (to ^ fa) {
      dfs (to, x);
      f[x] += Calc (f[to]);
    }
  }
  ans.insert (f[x]);
}

int main () {
  ios :: sync_with_stdio (0), cin.tie (0);
  cin >> n;
  for (int i = 1, x, y; i < n; ++i) {
    cin >> x >> y;
    g[x].push_back (y), g[y].push_back (x);
  }
  dfs (1, 0);
  return cout << ans.size (), 0 ^ 0;
}

無根樹的話你就換根一下,把每個點為根的哈希值求和比較就行了。