題意
- 給你一個個點的樹A,一個個點的樹B,求A樹有多少個不同的生成子圖與B同構。()
我們首先可以枚舉B樹是哪個點作爲根,B樹同構的情況只能算一次,有一個DP就是設表示A樹上點與B樹上點匹配的方案數。我們每次遍歷A樹的時候多記一個表示當前點的前個兒子把集合的點一一對應的方案數,這個東西做一個揹包就可以了。
B樹自身子樹同構的情況可能會導致一個點被重複匹配,那麼對於B中所有深度的子樹,假設某個深度有棵同構,那麼對與當前點作爲根的答案除即可。
#include<bits/stdc++.h>
#define pb push_back
#define Set(a, b) memset(a, b, sizeof(a))
#define For(i, a, b) for (int i = a; i <= b; ++ i)
using namespace std;
using ull = unsigned long long;
const int M = 12;
const int N = 2e3;
const int Base = 233;
const int mod = 1e9 + 7;
unordered_set<ull> vis;
vector<int> Ga[N + 5];
vector<int> Gb[M + 5];
int n, m, rt, coef, ans;
int g[N + 5][(1 << M) + 5];
int f[N + 5][M + 5], fa[N + 5];
int qpow(int _, int __) {
int ___ = 1;
for (; __; __ >>= 1, _ = 1ll * _ * _ % mod)
if (__ & 1) ___ = 1ll * ___ * _ % mod;
return ___;
}
ull dfs(int u, int dad) {
vector<ull> S;
ull res = Base;
for (auto v : Gb[u]) if (v ^ dad)
fa[v] = u, S.pb(dfs(v, u));
sort(S.begin(), S.end());
int sz = S.size(), len = 0;
For(i, 0, sz - 1) {
if (i && S[i] == S[i - 1]) ++ len;
else len = 1;
res += S[i];
coef = 1ll * qpow(len, mod - 2) * coef % mod;
}
return res * res;
}
void DFS(int u, int dad) {
for (auto v : Ga[u]) if (v ^ dad) DFS(v, u);
For(j, 1, m) {
int tp[M + 5], cnt = 0, id = 0, all;
for (auto v : Gb[j]) if (v ^ fa[j]) tp[++ cnt] = v;
all = 1 << cnt, g[0][0] = 1;
for (auto v : Ga[u]) {
++ id;
For(S, 0, all - 1) g[id][S] = g[id - 1][S];
For(S, 0, all - 1) For(k, 1, cnt) if (S >> (k - 1) & 1)
(g[id][S] += 1ll * f[v][tp[k]] * g[id - 1][S ^ 1 << (k - 1)] % mod) %= mod;
}
(f[u][j] += g[id][all - 1]) %= mod;
For(k, 0, id) For(S, 0, all - 1) g[k][S] = 0;
}
}
int main() {
freopen("tree.in", "r", stdin);
freopen("tree.out", "w", stdout);
int x, y;
scanf("%d", &n);
For(i, 2, n) {
scanf("%d%d", &x, &y);
Ga[x].pb(y), Ga[y].pb(x);
}
scanf("%d", &m);
For(i, 2, m) {
scanf("%d%d", &x, &y);
Gb[x].pb(y), Gb[y].pb(x);
}
For(i, 1, m) {
fa[rt = i] = 0, coef = 1;
ull hs = dfs(rt, 0);
if (vis.count(hs)) continue;
vis.insert(hs), DFS(1, 0);
For(j, 1, n) (ans += 1ll * coef * f[j][i] % mod) %= mod;
Set(f, 0);
}
cout << ans << endl;
return 0;
}
// hash B
// 枚舉B中每個點爲根 貼到A樹上
// f[i][j] A中的i與B中的j 對應的方案數
// 自身兒子同構的話除階乘。
// g[i][S] 只用前i個點把S中的點對應完的方案數