#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
  return a < b ? a = b, 1 : 0;
}
const int oo = 0x3f3f3f3f;
const int Mod = 1e9 + 7;
const int maxn = 1000, maxm = 12;
int n, m;
vector<int> adj[maxn + 5], adjf[maxm + 5];
map<int, vector<int> > way;
inline int blen(int first) { return 32 - __builtin_clz(first); }
inline int combine(int first, int second) {
  return first << blen(second) | second;
}
int dfsf(int first, int f = -1) {
  vector<int> s;
  for (auto second : adjf[first])
    if (second != f) s.push_back(dfsf(second, first));
  sort((s).begin(), (s).end());
  int ret = 1;
  for (auto u : s) ret = combine(ret, u);
  ret <<= 1;
  if (!way.count(ret)) way[ret] = s;
  return ret;
}
int ans;
map<int, int> dp[maxn + 5];
void dfs(int first, int f = -1) {
  vector<int> chd;
  for (auto second : adj[first])
    if (second != f) {
      chd.push_back(second);
      dfs(second, first);
    }
  for (const auto &u : way) {
    auto &v = u.second;
    int N = (int((u.second).size()));
    static int pd[(1 << maxm) + 5];
    memset(pd, 0, sizeof(pd[0]) * (1 << N));
    pd[0] = 1;
    for (auto second : chd) {
      static int nxt[(1 << maxm) + 5];
      memcpy(nxt, pd, sizeof(nxt[0]) * (1 << N));
      for (int i = (0), i_end_ = (N); i < i_end_; ++i) {
        int num = dp[second][v[i]];
        if (!num) continue;
        for (int j = (1 << N) - 1; j >= 0; --j)
          if (pd[j] && !(j >> i & 1) &&
              !(i && v[i] == v[i - 1] && !(j >> (i - 1) & 1)))
            (nxt[j | (1 << i)] += (long long)pd[j] * num % Mod) %= Mod;
      }
      memcpy(pd, nxt, sizeof(pd[0]) * (1 << N));
    }
    if (pd[(1 << N) - 1]) {
      dp[first][u.first] = pd[(1 << N) - 1];
      if (blen(u.first) == (m << 1)) (ans += pd[(1 << N) - 1]) %= Mod;
    }
  }
}
int main() {
  scanf("%d", &n);
  for (int i = (0), i_end_ = (n - 1); i < i_end_; ++i) {
    int u, v;
    scanf("%d%d", &u, &v), --u, --v;
    adj[u].push_back(v), adj[v].push_back(u);
  }
  scanf("%d", &m);
  for (int i = (0), i_end_ = (m - 1); i < i_end_; ++i) {
    int u, v;
    scanf("%d%d", &u, &v), --u, --v;
    adjf[u].push_back(v), adjf[v].push_back(u);
  }
  for (int i = (0), i_end_ = (m); i < i_end_; ++i) dfsf(i);
  ans = 0;
  dfs(0);
  (ans += Mod) %= Mod;
  printf("%d\n", ans);
  return 0;
}
