#include <bits/stdc++.h>
const int N = 1005, M = 12, mod = 1000000007;
int n, m;
struct vector {
  int a[N], _size;
  inline int &operator[](int index) { return a[index]; }
  inline void emplace_back(int x) { a[_size++] = x; }
  inline void clear() { _size = 0; }
  inline int size() { return _size; }
};
struct tree {
  vector son[N + 1];
  int head[N], tot, sons[N];
  struct edge {
    int to, nxt;
  } e[N << 1];
  void link(int x, int y) {
    e[++tot] = (edge){y, head[x]}, head[x] = tot;
    e[++tot] = (edge){x, head[y]}, head[y] = tot;
  }
  void dfs(int x, int f = 0) {
    son[x].clear(), sons[x - 1] = 0;
    for (int i = head[x]; i; i = e[i].nxt)
      if (e[i].to != f)
        son[x].emplace_back(e[i].to), dfs(e[i].to, x),
            sons[x - 1] |= 1 << e[i].to - 1;
  }
} a, b;
inline void up(int &x, int y) { x += y - mod, x += x >> 31 & mod; }
inline void up(int &x, int y, int z) { x = (x + (long long)y * z) % mod; }
int pow(int x, int y, int ans = 1) {
  for (; y; y >>= 1, x = (long long)x * x % mod)
    if (y & 1) ans = (long long)ans * x % mod;
  return ans;
}
int dp[N][1 << M];
int dfs(int x, int id, int status) {
  if (id == a.son[x].size()) return status == 0;
  int y = a.son[x][id];
  if (~dp[y][status]) return dp[y][status];
  int &ret = dp[y][status] = dfs(x, id + 1, status);
  for (int s = status, i = __builtin_ctz(s); s; i = __builtin_ctz(s &= s - 1))
    up(ret, dfs(y, 0, b.sons[i]), dfs(x, id + 1, status ^ 1 << i));
  return ret;
}
int main() {
  std::ios::sync_with_stdio(0), std::cin.tie(0);
  std::cin >> n;
  for (int i = 1, x, y; i < n; ++i) std::cin >> x >> y, a.link(x, y);
  std::cin >> m;
  for (int i = 1, x, y; i < m; ++i) std::cin >> x >> y, b.link(x, y);
  a.dfs(1);
  int ans = 0, type = 0;
  for (int root = 1; root <= m; ++root) {
    std::memset(dp, -1, sizeof dp), b.dfs(root);
    for (int i = 1; i <= n; ++i) up(ans, dfs(i, 0, b.sons[root - 1]));
  }
  a = b, a.dfs(1);
  for (int root = 1; root <= m; ++root) {
    std::memset(dp, -1, sizeof dp), b.dfs(root);
    up(type, dfs(1, 0, b.sons[root - 1]));
  }
  std::cout << pow(type, mod - 2, ans) << '\n';
  return 0;
}
