#include <bits/stdc++.h>
using namespace std;
const int MX = 1005, mod = 1000000007;
int n, m, x, y, mx = -1e9;
long long res;
vector<int> s[MX], t[MX];
void add(pair<int, int> &p, int x) {
  if (x > p.first) {
    p.second = p.first;
    p.first = x;
  } else if (x > p.second) {
    p.second = x;
  }
}
pair<int, int> dfs(int u, int p) {
  pair<int, int> res(-1, -1);
  for (int v : t[u])
    if (v != p) {
      pair<int, int> p = dfs(v, u);
      if (p.first != -1) add(res, p.first + 1);
    }
  if (res.first == -1) res.first = 0;
  return res;
}
map<vector<int>, int> mp;
int hsh[MX];
vector<int> ch[MX];
void obtHash(int u, int p) {
  vector<int> res;
  for (int v : t[u])
    if (v != p) {
      obtHash(v, u);
      res.push_back(hsh[v]);
    }
  sort(res.begin(), res.end());
  if (!mp.count(res)) {
    int sz = mp.size();
    mp[res] = sz;
    ch[sz] = res;
  }
  hsh[u] = mp[res];
}
map<int, int> mem;
long long cn[MX][(1 << 12) + 1];
long long dp(int u, int p, int k) {
  if (!k) return 1;
  int id = MX * MX * u + MX * p + k;
  if (mem.count(id)) return mem[id];
  int &res = mem[id];
  vector<int> &f = ch[k];
  int n = f.size();
  for (int i = 0; i < (1 << n); i++) cn[u][i] = 0;
  cn[u][0] = 1;
  int i = 0;
  for (int v : s[u])
    if (v != p)
      for (int mk = (1 << n) - 1; mk >= 0; mk--)
        for (int j = 0; j < n; j++)
          if (!(mk & (1 << j)) &&
              (j == 0 || f[j] != f[j - 1] || (mk & (1 << j - 1))))
            (cn[u][mk | (1 << j)] += cn[u][mk] * dp(v, u, f[j])) %= mod;
  res = cn[u][(1 << n) - 1];
  return res;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  for (int i = 0; i < n - 1; i++) {
    int a, b;
    cin >> a >> b;
    s[a].push_back(b);
    s[b].push_back(a);
  }
  cin >> m;
  for (int i = 0; i < m - 1; i++) {
    int a, b;
    cin >> a >> b;
    t[a].push_back(b);
    t[b].push_back(a);
  }
  for (int i = 1; i <= m; i++) {
    pair<int, int> p = dfs(i, -1);
    if (p.second > mx) {
      mx = p.second;
      x = i;
      y = -1;
    } else if (p.second == mx) {
      y = i;
    }
  }
  mp[{}] = 0;
  obtHash(x, y);
  if (y != -1) obtHash(y, x);
  if (y == -1) {
    for (int u = 1; u <= n; u++) (res += dp(u, 0, hsh[x])) %= mod;
  } else {
    for (int u = 1; u <= n; u++)
      for (int v : s[u])
        if (u < v) {
          (res += dp(u, v, hsh[x]) * dp(v, u, hsh[y])) %= mod;
          if (hsh[x] != hsh[y])
            (res += dp(u, v, hsh[y]) * dp(v, u, hsh[x])) %= mod;
        }
  }
  cout << res << '\n';
  return 0;
}
