#include <bits/stdc++.h>
using namespace std;
const int mo = 1000000007;
const int N = 100005;
int n, sz[N], m;
int q[N * 50], qq[N * 50];
long long b[N * 50];
vector<int> e[N];
void dfs(int x, int fa) {
  sz[x] = 1;
  for (auto i : e[x])
    if (i != fa) {
      dfs(i, x);
      sz[x] += sz[i];
      b[++*b] = 1ll * sz[i] * (n - sz[i]);
    }
}
void solve() {
  *b = 0;
  scanf("%d", &n);
  for (int i = (int)(1); i <= (int)(n); i++) e[i].resize(0);
  for (int i = (int)(1); i <= (int)(n - 1); i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    e[x].push_back(y);
    e[y].push_back(x);
  }
  *q = 0;
  scanf("%d", &m);
  for (int i = (int)(1); i <= (int)(m); i++) {
    int x;
    scanf("%d", &x);
    for (int j = 2; j * j <= x; j++)
      for (; x % j == 0; x /= j, q[++*q] = j)
        ;
    if (x != 1) q[++*q] = x;
  }
  sort(q + 1, q + *q + 1);
  if (*q < n) {
    for (int i = (int)(1); i <= (int)(n - 1); i++) qq[i] = 1;
    for (int i = (int)(1); i <= (int)(*q); i++) qq[n - 1 - (*q - i)] = q[i];
  } else {
    for (int i = (int)(1); i <= (int)(n - 1); i++) qq[i] = 1;
    for (int i = (int)(1); i <= (int)(n - 1); i++) qq[i] = q[i];
    for (int i = (int)(n); i <= (int)(*q); i++)
      qq[n - 1] = 1ll * qq[n - 1] * q[i] % mo;
  }
  dfs(1, 0);
  sort(b + 1, b + n);
  int ans = 0;
  for (int i = (int)(1); i <= (int)(n - 1); i++)
    ans = (ans + b[i] % mo * qq[i]) % mo;
  printf("%d\n", ans);
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) solve();
}
