#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
int i, j, k, n, m, s, t, ans1, ans2, ans;
int dp[1005][1 << 12];
struct Tree {
  int head[1005];
  struct edge {
    int vet, next;
  } E[2005];
  int son[1005];
  int num[1005];
  int a[1005][1005];
  int n, tot;
  Tree() {
    memset(head, -1, sizeof(head));
    tot = -1;
  }
  void add(int u, int v) {
    E[++tot] = (edge){v, head[u]};
    head[u] = tot;
  }
  void read() {
    scanf("%d", &n);
    for (int i = 1; i < n; i++) {
      int x, y;
      scanf("%d%d", &x, &y);
      add(x, y);
      add(y, x);
    }
  }
  void dfs(int u, int dad) {
    son[u] = 0;
    for (int e = head[u]; e != -1; e = E[e].next)
      if (e != dad) {
        son[u] |= 1 << (E[e].vet - 1);
        dfs(E[e].vet, e ^ 1);
      }
  }
  void getsize(int u, int dad) {
    num[u] = 0;
    for (int e = head[u]; e != -1; e = E[e].next)
      if (e != dad) {
        a[u][++num[u]] = E[e].vet;
        getsize(E[e].vet, e ^ 1);
      }
  }
} S, T;
int powmod(const int &x, int y) {
  if (y == 0) return 1;
  int ret = powmod(x, y >> 1);
  if (y & 1)
    ret = (long long)ret * ret % mod * x % mod;
  else
    ret = (long long)ret * ret % mod;
  return ret;
}
int dfs(int u, int num, int opt) {
  if (num == 0) return opt == 0;
  int x = S.a[u][num];
  if (dp[x][opt] != -1) return dp[x][opt];
  dp[x][opt] = dfs(u, num - 1, opt);
  for (int i = 0; i < T.n; i++)
    if ((1 << i) & opt) {
      dp[x][opt] += (long long)dfs(u, num - 1, opt ^ (1 << i)) *
                    dfs(x, S.num[x], T.son[i + 1]) % mod;
      if (dp[x][opt] >= mod) dp[x][opt] -= mod;
    }
  return dp[x][opt];
}
int main() {
  S.read();
  T.read();
  S.getsize(1, -1);
  for (int j = 1; j <= T.n; j++) {
    memset(dp, -1, sizeof(dp));
    T.dfs(j, -1);
    for (int i = 1; i <= S.n; i++) {
      ans1 += dfs(i, S.num[i], T.son[j]);
      if (ans1 >= mod) ans1 -= mod;
    }
  }
  S = T;
  S.getsize(1, -1);
  for (int j = 1; j <= T.n; j++) {
    memset(dp, -1, sizeof(dp));
    T.dfs(j, -1);
    ans2 += dfs(1, S.num[1], T.son[j]);
    if (ans2 >= mod) ans2 -= mod;
  }
  ans = (long long)ans1 * powmod(ans2, mod - 2) % mod;
  printf("%d\n", ans);
  return 0;
}
