#include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
  puts(f ? "YES" : "NO");
  exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
  x += y;
  if (x >= mod) x -= mod;
  assert(x >= 0 && x < mod);
}
void et() {
  puts("-1");
  exit(0);
}
int ans;
int len(int x) { return 32 - __builtin_clz(x); }
void jin(int &x, int y) { x = (x << len(y)) | y; }
unordered_map<int, int> num[1005];
int f[2][1 << 12];
struct mb {
  vector<int> mp[1005];
  int n;
  map<int, vector<int>> idm;
  void rd() {
    scanf("%d", &n);
    for (int i = 0, u, v; i < n - 1; i++) {
      scanf("%d%d", &u, &v);
      mp[u].push_back(v);
      mp[v].push_back(u);
    };
  }
  int dfs(int x, int pa) {
    vector<int> tmp;
    for (int c : mp[x])
      if (c != pa) tmp.push_back(dfs(c, x));
    sort(tmp.begin(), tmp.end());
    int res = 1;
    for (int z : tmp) jin(res, z);
    res <<= 1;
    if (idm.find(res) == idm.end()) idm[res] = tmp;
    return res;
  }
  void cal() {
    for (int(i) = 1; (i) <= (int)(n); (i)++) dfs(i, 0);
  }
  void wk(int x, int pa, mb &T) {
    for (int c : mp[x])
      if (c != pa) wk(c, x, T);
    for (auto &pi : T.idm) {
      auto &V = pi.second;
      int id = pi.first, N = V.size();
      int tt = 0;
      for (int(j) = 0; (j) < (int)(1 << N); (j)++) f[0][j] = f[1][j] = 0;
      f[0][0] = 1;
      for (int c : mp[x])
        if (c != pa) {
          int pre = tt, cur = tt ^ 1;
          tt ^= 1;
          for (int(j) = 0; (j) < (int)(1 << N); (j)++) f[cur][j] = f[pre][j];
          for (int(i) = 0; (i) < (int)(N); (i)++) {
            if (num[c][V[i]]) {
              for (int j = (1 << N) - 1; ~j; j--) {
                if (f[pre][j] && !((1 << i) & j) &&
                    !(i && V[i] == V[i - 1] && !((1 << (i - 1)) & j))) {
                  addmod(f[cur][j | (1 << i)],
                         (long long)num[c][V[i]] * f[pre][j] % 1000000007);
                }
              }
            }
          }
        }
      if (f[tt][(1 << N) - 1]) {
        num[x][id] = f[tt][(1 << N) - 1];
        if (len(id) == 2 * T.n) {
          addmod(ans, f[tt][(1 << N) - 1]);
        }
      }
    }
  }
} s, t;
void fmain(int tid) {
  s.rd();
  t.rd();
  t.cal();
  s.wk(1, 0, t);
  printf("%d\n", ans);
}
int main() {
  int t = 1;
  for (int(i) = 1; (i) <= (int)(t); (i)++) {
    fmain(i);
  }
  return 0;
}
