#include <bits/stdc++.h>
using namespace std;
const int N = 2002;
const int M = N << 1;
const int pri[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 29, 31, 37, 41, 43, 47};
int n, p, m;
int cnt, head[N], Next[M], v[M];
vector<int> g[20];
void read(int &x) { scanf("%d", &x); }
void Add(long long &x, long long y) {
  x += y;
  while (x >= p) x -= p;
  while (x < 0) x += p;
}
void Add(int &x, int y) {
  x += y;
  while (x >= p) x -= p;
  while (x < 0) x += p;
}
void add(int x, int y) {
  Next[++cnt] = head[x];
  head[x] = cnt;
  v[cnt] = y;
}
long long h[20];
int sz[20], pre[20], ff[20];
int ch[20][20], ss[20];
void predfs(int x, int fa) {
  h[x] = sz[x] = 1;
  ff[x] = fa;
  map<long long, int> mp;
  ss[x] = 0;
  for (int i = (0); i < (g[x].size()); i++)
    if (g[x][i] != fa) {
      int tmp = g[x][i];
      ch[x][ss[x]++] = tmp;
      predfs(tmp, x);
      sz[x] += sz[tmp];
      h[x] += pri[sz[tmp]] * h[tmp];
      if (mp.count(h[tmp]))
        pre[tmp] = mp[h[tmp]];
      else
        pre[tmp] = -1;
      mp[h[tmp]] = ss[x] - 1;
    }
}
int dp[N][13];
int f[1 << 13];
void dfs(int x, int fa) {
  for (int i = head[x]; i; i = Next[i])
    if (v[i] != fa) dfs(v[i], x);
  for (int o = (1); o <= (m); o++) {
    int all = ss[o];
    all = (1 << all) - 1;
    for (int i = (0); i <= (all); i++) f[i] = 0;
    f[0] = 1;
    for (int uu = head[x]; uu; uu = Next[uu]) {
      int tmp = v[uu];
      if (tmp == fa) continue;
      for (int mask = (all); mask >= (0); mask--)
        for (int i = (0); i < (ss[o]); i++)
          if (!(mask & (1 << i)) &&
              (pre[ch[o][i]] == -1 || (mask & (1 << pre[ch[o][i]])))) {
            Add(f[mask | (1 << i)], 1LL * f[mask] * dp[tmp][ch[o][i]] % p);
          }
    }
    dp[x][o] = f[all];
  }
}
map<long long, int> mp;
int ans;
void solve(int rt) {
  pre[rt] = -1;
  predfs(rt, 0);
  if (mp[h[rt]]) return;
  mp[h[rt]] = 1;
  memset(dp, 0, sizeof 0);
  dfs(1, 0);
  for (int i = (1); i <= (n); i++) Add(ans, dp[i][rt]);
}
int main() {
  read(n);
  int x, y;
  for (int i = (2); i <= (n); i++) {
    read(x);
    read(y);
    add(x, y);
    add(y, x);
  }
  read(m);
  for (int i = (2); i <= (m); i++) {
    read(x);
    read(y);
    g[x].push_back(y);
    g[y].push_back(x);
  }
  p = 1e9 + 7;
  for (int i = (1); i <= (m); i++) solve(i);
  cout << ans << endl;
  return 0;
}
