#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const int mod = 1e9 + 7;
vector<int> g[1010], t[13];
int n, m, st[13], ty[1 << 12];
int qpow(int a, int b) {
  int c = 1;
  for (; b; b >>= 1) {
    if (b & 1) c = 1ll * a * c % mod;
    a = 1ll * a * a % mod;
  }
  return c;
}
void Dfs(int x, int fa) {
  st[x] = 0;
  for (int i = 0, v; i < t[x].size(); i++) {
    v = t[x][i];
    if (v == fa) continue;
    Dfs(v, x);
    st[x] |= (1 << (v - 1));
  }
}
int dp[1010][1 << 12];
void dfs(int x, int fa) {
  dp[x][0] = 1;
  for (int i = 0, v; i < g[x].size(); i++) {
    v = g[x][i];
    if (v == fa) continue;
    dfs(v, x);
    for (int s = (1 << m) - 1; s >= 0; s--)
      if (dp[x][s])
        for (int k = 0; k < m; k++)
          if (!s || ((st[ty[s]] >> k) & 1) && (!((s >> k) & 1)))
            (dp[x][s | (1 << k)] += 1ll * dp[x][s] * dp[v][st[k + 1]] % mod) %=
                mod;
  }
}
int solve() {
  int ans = 0;
  for (int rt = 1; rt <= m; rt++) {
    Dfs(rt, 0);
    for (int s = 1; s < (1 << m); s++)
      for (int j = 1; j <= m; j++)
        if ((s | st[j]) == st[j]) ty[s] = j;
    memset(dp, 0, sizeof(dp));
    dfs(1, 0);
    for (int i = 1; i <= n; i++) (ans += dp[i][st[rt]]) %= mod;
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 1, u, v; i < n; i++)
    scanf("%d%d", &u, &v), g[u].push_back(v), g[v].push_back(u);
  scanf("%d", &m);
  for (int i = 1, u, v; i < m; i++)
    scanf("%d%d", &u, &v), t[u].push_back(v), t[v].push_back(u);
  int ans = solve();
  for (int i = 1; i <= n; i++) g[i].clear();
  n = m;
  for (int i = 1; i <= m; i++) g[i] = t[i];
  return printf("%d\n", 1ll * ans * qpow(solve(), mod - 2) % mod), 0;
}
