#include <bits/stdc++.h>
int CH, NEG;
template <typename TP>
inline void read(TP &ret) {
  ret = NEG = 0;
  while (CH = getchar(), CH < '!')
    ;
  if (CH == '-') NEG = true, CH = getchar();
  while (ret = ret * 10 + CH - '0', CH = getchar(), CH > '!')
    ;
  if (NEG) ret = -ret;
}
using namespace std;
int n, m, ANS;
int now[(1 << 12LL) + 5], nxt[(1 << 12LL) + 5];
vector<int> G[1000LL + 5], g[12LL + 5];
map<int, vector<int> > STA;
map<int, int> ans[1000LL + 5];
inline int blen(int x) { return 32 - __builtin_clz(x); }
inline int combine(int x, int y) { return x << blen(y) | y; }
inline void P(int x) {
  for (int i = 30; ~i; i--) {
    printf("%d", int(bool(x & (1 << i))));
  }
  puts("");
}
int dfs0(int u, int fa = 0) {
  int h = 1;
  vector<int> H;
  for (auto v : g[u])
    if (v != fa) H.push_back(dfs0(v, u));
  sort(H.begin(), H.end());
  for (auto s : H) h = combine(h, s);
  h <<= 1;
  if (!STA.count(h)) STA[h] = H;
  return h;
}
void dfs(int u, int fa = 0) {
  vector<int> chd;
  for (auto v : G[u])
    if (v != fa) chd.push_back(v), dfs(v, u);
  for (const auto &sta : STA) {
    auto &H = sta.second;
    int h = sta.first, N = H.size();
    memset(now, 0, sizeof(int) * (1 << N));
    now[0] = 1;
    for (auto ch : chd) {
      memcpy(nxt, now, sizeof(int) * (1 << N));
      for (int i = 0; i < N; i++) {
        int num = ans[ch][H[i]];
        if (!num) continue;
        for (int j = (1 << N) - 1; j >= 0; j--)
          if (now[j] && !(j >> i & 1) &&
              !(i && H[i] == H[i - 1] && !(j >> (i - 1) & 1)))
            (nxt[j | (1 << i)] += (long long)now[j] * num % 1000000007LL) %=
                1000000007LL;
      }
      memcpy(now, nxt, sizeof(int) * (1 << N));
    }
    if (now[(1 << N) - 1]) {
      ans[u][h] = now[(1 << N) - 1];
      if (blen(h) == (m << 1)) (ANS += now[(1 << N) - 1]) %= 1000000007LL;
    }
  }
}
int main() {
  int i, u, v;
  read(n);
  for (i = (1); i < (n); i++)
    read(u), read(v), G[u].push_back(v), G[v].push_back(u);
  read(m);
  for (i = (1); i < (m); i++)
    read(u), read(v), g[u].push_back(v), g[v].push_back(u);
  for (i = (1); i <= (m); i++) dfs0(i);
  dfs(1);
  (ANS += 1000000007LL) %= 1000000007LL;
  printf("%d\n", ANS);
END:
  getchar(), getchar();
  return 0;
}
