You are given a tree that consists of $n$ nodes. You should label each of its $n-1$ edges with an integer in such way that satisfies the following conditions:   each integer must be greater than $0$;  the product of all $n-1$ numbers should be equal to $k$;  the number of $1$-s among all $n-1$ integers must be minimum possible. 

Let's define $f(u,v)$ as the sum of the numbers on the simple path from node $u$ to node $v$. Also, let $\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$ be a distribution index of the tree.

Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $10^9 + 7$.

In this problem, since the number $k$ can be large, the result of the prime factorization of $k$ is given instead.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

The first line of each test case contains a single integer $n$ ($2 \le n \le 10^5$) — the number of nodes in the tree.

Each of the next $n-1$ lines describes an edge: the $i$-th line contains two integers $u_i$ and $v_i$ ($1 \le u_i, v_i \le n$; $u_i \ne v_i$) — indices of vertices connected by the $i$-th edge.

Next line contains a single integer $m$ ($1 \le m \le 6 \cdot 10^4$) — the number of prime factors of $k$.

Next line contains $m$ prime numbers $p_1, p_2, \ldots, p_m$ ($2 \le p_i < 6 \cdot 10^4$) such that $k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$, the sum of $m$ over all test cases doesn't exceed $6 \cdot 10^4$, and the given edges for each test cases form a tree.


-----Output-----

Print the maximum distribution index you can get. Since answer can be too large, print it modulo $10^9+7$.


-----Example-----
Input
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3

Output
17
18
286



-----Note-----

 In the first test case, one of the optimal ways is on the following image:

 [Image] 

 In this case, $f(1,2)=1$, $f(1,3)=3$, $f(1,4)=5$, $f(2,3)=2$, $f(2,4)=4$, $f(3,4)=2$, so the sum of these $6$ numbers is $17$.

 In the second test case, one of the optimal ways is on the following image:

 [Image] 

 In this case, $f(1,2)=3$, $f(1,3)=1$, $f(1,4)=4$, $f(2,3)=2$, $f(2,4)=5$, $f(3,4)=3$, so the sum of these $6$ numbers is $18$.

Difficulty: MEDIUM_HARD
Tags: Graph traversal

Sorting

Implementation

Greedy algorithms

Number theory

Tree algorithms

Dynamic programming

Mathematics
Skill types: Dynamic programming

Sorting

Greedy algorithms

Starter code:

Solutions:
import sys
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
mod = 10 ** 9 + 7
input = sys.stdin.readline
mod = 10 ** 9 + 7
for tc in range(int(input())):
	(n,) = I()
	g = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(x, y) = I()
		g[x].append(y)
		g[y].append(x)
	(m,) = I()
	l = sorted(I())
	if m < n - 1:
		l = [1] * (n - 1 - m) + l
	else:
		temp = 1
		for j in range(m - n + 1):
			temp = temp * l[-j - 1] % mod
		l[n - 2] = l[n - 2] * temp % mod
	odr = []
	st = [1]
	visi = [0] * (n + 1)
	visi[1] = 1
	par = [-1] * (n + 1)
	while st:
		x = st.pop()
		odr.append(x)
		for to in g[x]:
			if visi[to] == 0:
				st.append(to)
				par[to] = x
				visi[to] = 1
	tem = [1] * (n + 1)
	te = []
	for x in odr[1:][::-1]:
		te.append(tem[x] * (n - tem[x]))
		tem[par[x]] += tem[x]
	te.sort()
	ans = 0
	for i in range(n - 1):
		ans = (ans + te[i] * l[i]) % mod
	print(ans)


for i in range(int(input())):
	n = int(input())
	tree = [[] for j in range(n)]
	paths = [0] * n
	degree = [1] * n
	branches = [0] * n
	for j in range(n - 1):
		(u, v) = map(int, input().split())
		tree[u - 1].append(v - 1)
		tree[v - 1].append(u - 1)
		branches[u - 1] += 1
		branches[v - 1] += 1
	k = 0
	for j in range(n - 1):
		if degree[j] == 1:
			v = j
			new_v = v
			while branches[v] == 1:
				paths[k] = degree[v]
				k += 1
				for vertex in tree[v]:
					if branches[vertex] != 1:
						new_v = vertex
						break
				if new_v == v:
					break
				branches[new_v] -= 1
				degree[new_v] += degree[v]
				v = new_v
	m = int(input())
	labels = sorted(list(map(int, input().split())))
	if m < n:
		labels = [1] * (n - 1 - m) + labels
	else:
		for element in labels[n - 1:]:
			labels[n - 2] = labels[n - 2] * element % (10 ** 9 + 7)
	paths.pop()
	paths = [item * (n - item) for item in paths]
	paths.sort()
	print(sum([paths[j] * labels[j] for j in range(n - 1)]) % (10 ** 9 + 7))


import sys
(_ord, inp, num, neg, _Index) = (lambda x: x, [], 0, False, 0)
(i, s) = (0, sys.stdin.buffer.read())
try:
	while True:
		if s[i] >= b'0'[0]:
			num = 10 * num + _ord(s[i]) - 48
		elif s[i] == b'-'[0]:
			neg = True
		elif s[i] != b'\r'[0]:
			inp.append(-num if neg else num)
			(num, neg) = (0, False)
		i += 1
except IndexError:
	pass
if s and s[-1] >= b'0'[0]:
	inp.append(-num if neg else num)

def fin(size=None):
	global _Index
	if size == None:
		ni = _Index
		_Index += 1
		return inp[ni]
	else:
		ni = _Index
		_Index += size
		return inp[ni:ni + size]
from types import GeneratorType

def recursive(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
gr = []
childs = []
n = 0

@recursive
def dfs(node, par):
	global gr, cost, n, childs
	su = 1
	for i in gr[node]:
		if i != par:
			yield dfs(i, node)
			su += childs[i]
			cost.append(childs[i] * (n - childs[i]))
	childs[node] = su
	yield
mod = 1000000007
_T_ = fin()
for _t_ in range(_T_):
	n = fin()
	gr = [[] for i in range(n + 1)]
	childs = [1 for i in range(n + 1)]
	cost = []
	for _ in range(n - 1):
		(u, v) = fin(2)
		gr[u].append(v)
		gr[v].append(u)
	m = fin()
	cm = fin(m)
	cm.sort()
	dfs(1, 0)
	cost.sort()
	ll = len(cost)
	if ll >= m:
		cm = [1 for i in range(ll - m)] + cm
	else:
		while len(cm) != ll:
			cm[-2] *= cm[-1]
			cm[-2] %= mod
			cm.pop()
	s = 0
	for i in range(ll):
		s += cm[i] % mod * (cost[i] % mod) % mod
		s %= mod
	print(s)


import threading
import sys
threading.stack_size(10 ** 8)
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
mod = 1000000007

def main():

	def dfs(p, cn, n):
		sz = 1
		for nn in g[cn]:
			if nn != p:
				x = dfs(cn, nn, n)
				pq.append(x * (n - x))
				sz += x
		return sz
	for test in range(int(input())):
		n = int(input())
		g = defaultdict(list)
		for _ in range(1, n):
			(u, v) = map(int, input().split())
			g[u].append(v)
			g[v].append(u)
		m = int(input())
		p = list(map(int, input().split()))
		while len(p) < n - 1:
			p.append(1)
		p.sort()
		pq = []
		dfs(-1, 1, n)
		pq.sort()
		res = 0
		for i in range(n - 2):
			res = (res + pq[i] * p[i]) % mod
		l = pq[n - 2]
		for i in range(n - 2, max(m, n - 1)):
			l = l * p[i] % mod
		res = (res + l) % mod
		print(res)
threading.Thread(target=main).start()


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	t = int(input())
	ans_a = []
	mod = 10 ** 9 + 7
	for ti in range(t):
		n = int(input())
		adj = [[] for _ in range(n)]
		edge_i = [[] for _ in range(n)]
		deg = [0] * n
		for (ei, (u, v)) in enumerate((map(int, input().split()) for _ in range(n - 1))):
			adj[u - 1].append(v - 1)
			adj[v - 1].append(u - 1)
			edge_i[u - 1].append(ei)
			edge_i[v - 1].append(ei)
			deg[u - 1] += 1
			deg[v - 1] += 1
		m = int(input())
		p = sorted(map(int, input().split()))
		path_cnt = []
		visited_edge = [0] * (n - 1)
		stack = [i for i in range(n) if deg[i] == 1]
		size = [1] * n
		while stack:
			v = stack.pop()
			for (dest, ei) in zip(adj[v], edge_i[v]):
				if visited_edge[ei]:
					continue
				visited_edge[ei] = 1
				path_cnt.append(size[v] * (n - size[v]))
				if deg[dest] == 0:
					continue
				size[dest] += size[v]
				deg[dest] -= 1
				if deg[dest] == 1:
					stack.append(dest)
		path_cnt.sort()
		while len(p) > n - 1:
			p[-1] = p.pop() * p[-1] % mod
		ans = 0
		while p:
			ans += path_cnt.pop() * p.pop() % mod
		ans = (ans + sum(path_cnt)) % mod
		ans_a.append(ans)
	output(*ans_a)
main()


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()

def addEdge(a, b):
	graph[a].append(b)
	graph[b].append(a)

def Bfs(src):
	q = deque([])
	q.append(src)
	visited[src] = True
	dist[src] = 0
	while q:
		node = q.popleft()
		for neighbour in graph[node]:
			if not visited[neighbour]:
				q.append(neighbour)
				visited[neighbour] = True
				dist[neighbour] = dist[node] + 1
				parent[neighbour] = node
				level[dist[neighbour]].append(neighbour)

def Bfs2(src):
	global total
	q = deque([])
	q.append(src)
	visited[src] = True
	while q:
		node = q.popleft()
		for neighbour in graph[node]:
			if not visited[neighbour]:
				q.append(neighbour)
				visited[neighbour] = True
				left = ct[neighbour]
				right = total - left
				times = left * right
				(a, b) = (node, neighbour)
				if a > b:
					(a, b) = (b, a)
				dic[a, b] = times
t = ip()
for _ in range(t):
	n = ip()
	total = n
	graph = [[] for i in range(n)]
	dist = [0] * n
	parent = [-1] * n
	visited = [False] * n
	ct = [0] * n
	dic = {}
	for i in range(n - 1):
		(a, b) = inp()
		(a, b) = (a - 1, b - 1)
		addEdge(a, b)
		if a > b:
			(a, b) = (b, a)
		dic[a, b] = 0
	m = ip()
	prime = list(inp())
	level = dd(list)
	Bfs(0)
	ch = sorted(list(level.keys()), reverse=True)
	visited = [False] * n
	ct[0] += 1
	for i in ch:
		for j in level[i]:
			ct[j] += 1
			par = parent[j]
			ct[par] += ct[j]
	Bfs2(0)
	prime.sort()
	if len(prime) <= n - 1:
		prime = [1] * (n - 1 - len(prime)) + prime
	else:
		ct = len(prime)
		while ct != n - 1:
			val = prime.pop()
			prime[-1] = prime[-1] * val % mod
			ct -= 1
	temp = sorted(list(dic.values()))
	ans = 0
	for i in range(n - 1):
		ans += temp[i] % mod * (prime[i] % mod) % mod
		ans %= mod
	print(ans)


import sys, threading

def dfs(curr, prev):
	sz[curr] = 1
	for i in graph[curr]:
		if i != prev:
			dfs(i, curr)
			sz[curr] += sz[i]

def main():
	for _ in range(int(input())):
		n = int(input())
		global graph
		graph = [[] for i in range(n)]
		for i in range(n - 1):
			(uu, vv) = [int(i) - 1 for i in input().split()]
			graph[uu].append(vv)
			graph[vv].append(uu)
		m = int(input())
		p = [int(i) for i in input().split()]
		p.sort()
		global sz
		sz = [0] * n
		dfs(0, 0)
		c = []
		mod = 10 ** 9 + 7
		for i in sz[1:]:
			c.append(i * (n - i))
		c.sort()
		ans = 0
		while len(p) > len(c):
			temp = p.pop()
			p[-1] *= temp
			p[-1] %= mod
		for i in range(n - 2, -1, -1):
			if len(p) > 0:
				ans += p.pop() * c.pop()
				ans %= mod
			else:
				ans += c.pop()
				ans %= mod
		print(ans)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


r = 10 ** 9 + 7
for _ in range(int(input())):
	N = int(input())
	V = [[] for i in range(N)]
	for i in range(N - 1):
		(u, v) = map(int, input().split())
		V[u - 1] += [v - 1]
		V[v - 1] += [u - 1]
	C = [[] for i in range(N)]
	P = [0] * N
	visited = [0] * N
	que = [0]
	visited[0] = 1
	while que:
		q = que.pop()
		for v in V[q]:
			if visited[v] == 0:
				visited[v] = 1
				C[q] += [v]
				P[v] = q
		que += C[q]
	que = [0]
	note = [1] * N
	while que:
		q = que.pop()
		if C[q]:
			que += [C[q].pop()]
		else:
			if q == 0:
				break
			note[P[q]] += note[q]
			que += [P[q]]
	for i in range(N):
		note[i] = note[i] * (N - note[i])
	note.sort()
	m = int(input())
	p = [1] * max(1, N - m) + list(map(int, input().split()))
	p.sort()
	for i in range(N, m + 1):
		p[N - 1] *= p[i]
		p[N - 1] %= r
	ans = 0
	for i in range(N):
		ans += p[i] * (note[i] % r) % r
		ans %= r
	print(ans)


import threading, sys
(*data,) = map(int, sys.stdin.read().split()[::-1])

def inp():
	return data.pop()
modulo = 10 ** 9 + 7

def dfssize(g, v, par, size, edges):
	for ch in g[v]:
		if ch != par:
			dfssize(g, ch, v, size, edges)
			size[v] += size[ch]
			edges.append(size[ch] * (len(g) - size[ch]))
	size[v] += 1

def mult(vals):
	ans = 1
	for v in vals:
		ans = ans * v % modulo
	return ans

def solve(g, kp):
	size = [0] * len(g)
	kp.sort()
	edges = []
	dfssize(g, 0, par=-1, size=size, edges=edges)
	n = len(g)
	if len(kp) > n - 1:
		kp[n - 2:] = [mult(kp[n - 2:])]
	while len(kp) < n - 1:
		kp = [1] * (n - 1 - len(kp)) + kp
	ans = 0
	edges.sort(reverse=True)
	kp = kp[::-1]
	for (a, b) in zip(edges, kp):
		ans += a * b
		ans %= modulo
	return ans
threading.stack_size(2 ** 27)
sys.setrecursionlimit(10 ** 5 + 100)

def main():
	for _ in range(int(inp())):
		n = int(inp())
		g = [[] for _ in range(n)]
		for _ in range(n - 1):
			(src, dst) = (inp(), inp())
			src -= 1
			dst -= 1
			g[src].append(dst)
			g[dst].append(src)
		m = int(inp())
		(*kp,) = [inp() for _ in range(m)]
		print(solve(g, kp))
t = threading.Thread(target=main)
t.start()
t.join()


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())

def tree_edge_descendant(graph, edge_time_count=False, root=0):
	edges = len(graph) - 1
	descendant_count = []
	stack_par = [[root]]
	stack_val = [[0]]
	while len(descendant_count) != edges:
		if not stack_par[-1]:
			del stack_par[-1], stack_val[-1]
			value = stack_val[-1].pop() + 1
			descendant_count.append(value)
			stack_val[-2][-1] += value
			if not stack_val:
				del stack_val[-1]
			continue
		vertex = stack_par[-1].pop()
		stack_par.append(list(graph[vertex]))
		stack_val.append([0] * len(graph[vertex]))
	if edge_time_count:
		return list(map(lambda x: x * (len(graph) - x), descendant_count))
	return descendant_count

def to_tree(graph, root=0):
	graph[:] = map(set, graph)
	stack = [[root]]
	while stack:
		if not stack[-1]:
			del stack[-1]
			continue
		vertex = stack[-1].pop()
		for e in graph[vertex]:
			graph[e].remove(vertex)
		stack.append(list(graph[vertex]))
	graph[:] = map(list, graph)
from functools import reduce
MOD = int(1000000000.0) + 7
g = []
for __ in range(itg()):
	n = itg()
	g = [list() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = mpint()
		g[u - 1].append(v - 1)
		g[v - 1].append(u - 1)
	to_tree(g)
	m = itg()
	factors = sorted(mpint())
	count = sorted(tree_edge_descendant(g, True))
	n -= 1
	if n >= m:
		factors = [1] * (n - m) + factors
	else:
		while len(factors) != n:
			factors[-1] = factors[-2] * factors.pop() % MOD
	print(reduce(lambda a, b: (a + b) % MOD, (time * value % MOD for (time, value) in zip(count, factors)), 0))


tests = int(input())
for t in range(tests):
	n = int(input())
	node_dict = {}
	for _ in range(n - 1):
		(u, v) = list(map(int, input().split()))
		if u in node_dict:
			node_dict[u][0] += 1
			node_dict[u][1].add(v)
		else:
			node_dict[u] = [1, set([v])]
		if v in node_dict:
			node_dict[v][0] += 1
			node_dict[v][1].add(u)
		else:
			node_dict[v] = [1, set([u])]
	num_primes = int(input())
	prime_ls = sorted(list(map(int, input().split())))
	edge_weight = []
	visit_node = [True for _ in range(0, n + 1)]
	other_node = list(node_dict[1][1])[0]
	stack = [[1, 0], [other_node, 0]]
	visit_node[1] = True
	node_dict[1][0] -= 1
	node_dict[1][1].remove(other_node)
	node_dict[other_node][0] -= 1
	node_dict[other_node][1].remove(1)
	while stack:
		(curr, excess) = stack[-1]
		visit_node[curr] = False
		if node_dict[curr][0] == 0:
			stack.pop()
			if stack:
				edge_weight.append((n - excess - 1) * (excess + 1))
				stack[-1][1] += 1 + excess
		else:
			new_node = node_dict[curr][1].pop()
			node_dict[curr][0] -= 1
			while node_dict[curr][0] != 0 and (not visit_node[new_node]):
				new_node = node_dict[curr][1].pop()
				node_dict[curr][0] -= 1
			if visit_node[new_node]:
				stack.append([new_node, 0])
	edge_weight = sorted(edge_weight)
	res = 0
	if num_primes > n - 1:
		prod = 1
		for idx in range(num_primes - 1, n - 3, -1):
			prod *= prime_ls[idx]
			prod = prod % 1000000007
		prime_ls[n - 2] = prod
		for idx in range(n - 1):
			res += edge_weight[idx] * prime_ls[idx] % 1000000007
			res = res % 1000000007
	else:
		start_idx = n - 2
		for idx in range(num_primes - 1, -1, -1):
			res += edge_weight[start_idx] * prime_ls[idx]
			res = res % 1000000007
			start_idx -= 1
		for idx in range(start_idx + 1):
			res += edge_weight[idx]
			res = res % 1000000007
	print(res % 1000000007)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
from types import GeneratorType

def bootstrap(func, stack=[]):

	def wrapped_function(*args, **kwargs):
		if stack:
			return func(*args, **kwargs)
		else:
			call = func(*args, **kwargs)
			while True:
				if type(call) is GeneratorType:
					stack.append(call)
					call = next(call)
				else:
					stack.pop()
					if not stack:
						break
					call = stack[-1].send(call)
			return call
	return wrapped_function
from math import gcd
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
	n = int(ri())
	g = [[] for i in range(n)]
	for i in range(n - 1):
		(a, b) = Ri()
		a -= 1
		b -= 1
		g[a].append(b)
		g[b].append(a)
	m = int(ri())
	fact = Ri()
	fact.sort(reverse=True)
	tot = 1
	nfact = []
	nfact.append(fact[0])
	for i in range(1, m):
		if m - i - 1 >= n - 2:
			nfact[0] = nfact[0] * fact[i] % MOD
		else:
			nfact.append(fact[i])
	fact = nfact
	nchild = [0] * n

	@bootstrap
	def dfs(cur, par):
		for child in g[cur]:
			if child == par:
				continue
			nchild[cur] += (yield dfs(child, cur))
		nchild[cur] += 1
		yield nchild[cur]
	dfs(0, -1)
	totans = []

	@bootstrap
	def dfs1(cur, par):
		for child in g[cur]:
			if child == par:
				continue
			totans.append((n - nchild[child]) * nchild[child])
			yield dfs1(child, cur)
		yield
	dfs1(0, -1)
	totans.sort(reverse=True)
	ans = 0
	cur = 0
	while cur < n - 1:
		if cur < m:
			ans += fact[cur] * totans[cur]
			ans = ans % MOD
		else:
			ans += totans[cur]
			ans = ans % MOD
		cur += 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
NUM = 10 ** 9 + 7

def dfs(x):
	vis[x] = 1
	stack = []
	stack.append(x)
	count = 0
	while len(stack) != N:
		s = stack[count]
		for i in range(len(adj[s])):
			t = adj[s][i]
			if vis[t] == 0:
				parent[t] = s
				vis[t] = 1
				val[t] = 1
				stack.append(t)
		count += 1
	while len(stack) != 0:
		r = stack.pop()
		val[parent[r]] += val[r]
from collections import *
for _ in range(int(input())):
	N = int(input())
	adj = defaultdict(list)
	for i in range(N - 1):
		(a, b) = list(map(int, input().split()))
		adj[a].append(b)
		adj[b].append(a)
	M = int(input())
	prime = list(map(int, input().split()))
	vis = [0] * (N + 1)
	val = [0] * (N + 1)
	parent = [0] * (N + 1)
	dfs(1)
	edges = []
	for i in range(1, N + 1):
		if i != 1:
			edges.append(val[i] * (N - val[i]))
	edges.sort(reverse=True)
	prime.sort(reverse=True)
	if M <= N - 1:
		ans = 0
		for i in range(len(prime)):
			ans = (ans + edges[i] * prime[i] % NUM) % NUM
		for i in range(len(prime), len(edges)):
			ans = (ans + edges[i] % NUM) % NUM
		print(ans % NUM)
	else:
		t = len(prime) - len(edges) + 1
		i = 0
		ans = 0
		val = 1
		for i in range(t):
			val = val * prime[i] % NUM
		ans = (ans + edges[0] * val % NUM) % NUM
		k = 1
		for j in range(t, len(prime)):
			ans = (ans + edges[k] * prime[j] % NUM) % NUM
			k += 1
		print(ans % NUM)


from sys import setrecursionlimit
from sys import stdin, stdout
from collections import deque
mod = int(1000000000.0 + 7)
test = int(stdin.readline())
for _ in range(test):
	n = int(stdin.readline())
	graph = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = map(int, stdin.readline().split())
		graph[u - 1].append(v - 1)
		graph[v - 1].append(u - 1)
	m = int(stdin.readline())
	f = [int(x) for x in stdin.readline().split()]
	visited = [False for i in range(n)]
	sub = [1 for i in range(n)]
	parent = [-1 for i in range(n)]
	q = deque([0])
	bfs = []
	visited[0] = True
	while q:
		u = q.popleft()
		for v in graph[u]:
			if not visited[v]:
				visited[v] = True
				bfs.append(v)
				parent[v] = u
				q.append(v)
	for i in bfs[::-1]:
		sub[parent[i]] += sub[i]
	cont = []
	for i in range(1, n):
		ans = sub[i] * (n - sub[i])
		cont.append(ans)
	for i in range(m, n - 1):
		f.append(1)
	f.sort()
	cont.sort()
	ans = 0
	while len(f) > n - 1:
		f[-2] = f[-1] * f[-2] % mod
		a = f.pop()
	for i in range(n - 1):
		ans = (ans + cont[i] % mod * f[i]) % mod
	print(int(ans))


import sys, threading
sys.setrecursionlimit(10 ** 6)
from collections import defaultdict as dft

def main():

	def dfs(nd):
		vis[nd] = 1
		d = 1
		for lnk in dct[nd]:
			if vis[lnk] == 0:
				num = dfs(lnk)
				d += num
		w.append(d * (n - d))
		return d
	mxn = 10 ** 9 + 7
	for _ in range(int(input())):
		n = int(input())
		w = []
		dct = dft(list)
		for i in range(n - 1):
			(a, b) = map(int, input().split())
			dct[a].append(b)
			dct[b].append(a)
		m = int(input())
		fac = list(map(int, input().split()))
		fac.sort()
		for xx in range(m - n + 1):
			if not fac:
				break
			temp = fac.pop()
			fac[-1] = fac[-1] * temp % mxn
			m -= 1
		res = 0
		vis = [0] * (n + 1)
		dfs(1)
		w.sort(reverse=True)
		for num in w:
			if not fac:
				temp = 1
			else:
				temp = fac.pop()
			res = (num * temp + res) % mxn
		print(res)
sys.setrecursionlimit(5 * 10 ** 5)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()


import sys
from collections import deque
input = sys.stdin.readline
for _ in range(int(input())):
	level = {}
	n = int(input())
	tree = {}
	edges = []
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		if a not in tree:
			tree[a] = []
		if b not in tree:
			tree[b] = []
		tree[a].append(b)
		tree[b].append(a)
		edges.append((a, b))
	m = int(input())
	p = list(map(int, input().split()))
	while len(p) < n - 1:
		p.append(1)
	stack = deque([1])
	seen = {}
	while stack:
		current = stack[0]
		if len(tree[current]) == 1 and current != 1:
			level[current] = 1
			stack.popleft()
		elif current in seen:
			for child in tree[current]:
				if child in level:
					level[current] = level.get(current, 1) + level[child]
			stack.popleft()
		else:
			for nxt in tree[current]:
				if nxt not in seen:
					stack.appendleft(nxt)
		seen[current] = 1
	frqs = []
	for edge in edges:
		a = edge[0]
		b = edge[1]
		if level[b] < level[a]:
			(a, b) = (b, a)
		frqs.append(level[a] * (n - level[a]))
	frqs.sort()
	p.sort()
	while len(p) > n - 1:
		p[n - 2] *= p.pop()
		p[n - 2] = p[n - 2] % 1000000007
	pr = 0
	for i in range(n - 1):
		pr += frqs[i] * p[i]
		pr = pr % 1000000007
	print(pr)


import sys, threading
from collections import defaultdict
input = sys.stdin.readline

def rl(type):
	return list(map(type, input().split()))

def main():
	MOD = 10 ** 9 + 7

	def create_graph(n):
		graph = defaultdict(list)
		for _ in range(n):
			(x, y) = map(int, input().split())
			graph[x].append(y)
			graph[y].append(x)
		return graph

	def walk(u, v):
		s = 1
		for i in graph[v]:
			if i != u:
				c = walk(v, i)
				w.append(c * (n - c))
				s += c
		return s
	for _ in range(int(input())):
		n = int(input())
		graph = create_graph(n - 1)
		k = int(input())
		arr = rl(int)
		if k < n - 1:
			arr += [1] * (n - 1 - k)
			arr.sort(reverse=True)
		else:
			arr.sort(reverse=True)
			while len(arr) != n - 1:
				temp = arr[0] * arr[1] % MOD
				arr.pop(0)
				arr[0] = temp
		w = []
		walk(0, 1)
		w.sort(reverse=True)
		result = 0
		for i in range(n - 1):
			result += w[i] % MOD * (arr[i] % MOD) % MOD
			result %= MOD
		print(result)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


import sys
from collections import deque
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	edge = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = list(map(int, input().split()))
		edge[u - 1].append(v - 1)
		edge[v - 1].append(u - 1)
	m = int(input())
	p = list(map(int, input().split()))
	size = [1 for i in range(n)]
	parent = [-1 for i in range(n)]
	res = []
	deq = deque([(0, -1)])
	while deq:
		(v, pv) = deq.popleft()
		res.append(v)
		for nv in edge[v]:
			if nv != pv:
				parent[nv] = v
				deq.append((nv, v))
	res = res[::-1]
	for v in res:
		for nv in edge[v]:
			if nv != parent[v]:
				size[v] += size[nv]
	coef = []
	for v in res:
		for nv in edge[v]:
			if nv != parent[v]:
				c = size[nv] * (n - size[nv])
				coef.append(c)
	mod = 10 ** 9 + 7
	if m < n - 1:
		res = 0
		coef.sort(reverse=True)
		p.sort(reverse=True)
		for i in range(m):
			res += coef[i] * p[i]
			res %= mod
		for i in range(m, n - 1):
			res += coef[i]
			res %= mod
		print(res)
	else:
		res = 0
		coef.sort()
		p.sort()
		for i in range(n - 2):
			res += coef[i] * p[i]
			res %= mod
		tmp = coef[-1]
		for i in range(n - 2, m):
			tmp *= p[i]
			tmp %= mod
		res = (res + tmp) % mod
		print(res)


import sys
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input().strip()

def listStr():
	return list(input().strip())
import collections as col
import math, itertools
MOD = 10 ** 9 + 7
from types import GeneratorType

def solve():

	def bootstrap(f, stack=[]):

		def wrappedfunc(*args, **kwargs):
			if stack:
				return f(*args, **kwargs)
			else:
				to = f(*args, **kwargs)
				while True:
					if type(to) is GeneratorType:
						stack.append(to)
						to = next(to)
					else:
						stack.pop()
						if not stack:
							break
						to = stack[-1].send(to)
				return to
		return wrappedfunc

	@bootstrap
	def numberOfNodes(s, e):
		subtree[s] = 1
		for u in graph[s]:
			if u == e:
				continue
			yield numberOfNodes(u, s)
			subtree[s] += subtree[u]
		yield
	N = getInt()
	edges = []
	graph = col.defaultdict(set)
	for n in range(N - 1):
		(U, V) = getInts()
		graph[U].add(V)
		graph[V].add(U)
		edges.append((min(U, V), max(U, V)))
	M = getInt()
	P = getInts()
	P.sort(reverse=True)
	subtree = [0] * (N + 1)
	numberOfNodes(1, 0)
	edge_conts = []
	for (U, V) in edges:
		x = min(subtree[U], subtree[V])
		edge_conts.append((N - x) * x)
	edge_conts.sort(reverse=True)
	ans = 0
	if M < N - 1:
		ans = sum(edge_conts[M:])
		edge_conts = edge_conts[:M]
	for i in range(len(edge_conts) - 1):
		p = P.pop()
		e = edge_conts.pop()
		ans += e * p
		ans %= MOD
	curr = 1
	for p in P:
		curr *= p
		curr %= MOD
	ans += edge_conts[0] * curr
	ans %= MOD
	return ans
for _ in range(getInt()):
	print(solve())


import sys
input = sys.stdin.readline

def DFS():
	stack = [1]
	visited = [0] * (n + 1)
	visited[1] = 1
	par = [0] * (n + 1)
	tp_stack = [1]
	while stack:
		new_stack = []
		for node in stack:
			for ne_node in e[node]:
				if visited[ne_node] == 0:
					visited[ne_node] = 1
					par[ne_node] = node
					new_stack.append(ne_node)
					tp_stack.append(ne_node)
		stack = list(new_stack)
	tp_stack = tp_stack[::-1]
	for node in tp_stack:
		if par[node] != 0:
			child[par[node]] += child[node]
			edge.append(child[node] * (n - child[node]))
	edge.sort()
for t in range(int(input())):
	n = int(input())
	child = [1] * (n + 1)
	e = [[] for i in range(n + 1)]
	edge = []
	mod = 1000000007
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		e[u].append(v)
		e[v].append(u)
	DFS()
	m = int(input())
	fac = list(map(int, input().split()))
	if m <= n - 1:
		for i in range(n - m - 1):
			fac.append(1)
		fac.sort()
	else:
		fac.sort()
		for i in range(n - 1, m):
			fac[n - 2] *= fac[i]
			fac[n - 2] %= mod
	ans = 0
	for i in range(n - 2, -1, -1):
		ans += edge[i] * fac[i]
		ans %= mod
	print(ans)


import sys
import heapq, functools, collections, itertools
import math, random
from collections import Counter, defaultdict
MOD = 10 ** 9 + 7
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def solve(edges, fact):
	console('----- solving ------')
	fact = sorted(fact)[::-1]
	edges = [(a - 1, b - 1) for (a, b) in edges]
	total_nodes = len(edges) + 1
	console('og fact', fact)
	if len(fact) >= len(edges):
		pdt = 1
		for x in fact[:len(fact) - len(edges) + 1]:
			pdt = pdt * x % MOD
		fact = [pdt] + fact[len(fact) - len(edges) + 1:]
	console('check', total_nodes, fact, edges)
	if len(fact) <= len(edges):
		fact = fact + [1] * (len(edges) - len(fact))
	nodes = []
	for (a, b) in edges:
		nodes.extend([a, b])
	c = Counter(nodes)
	starting_leaf = sorted(c.items(), key=lambda x: x[1])[0][0]
	g = defaultdict(list)
	for (a, b) in edges:
		g[a].append(b)
		g[b].append(a)
	console(starting_leaf)
	assert len(g[starting_leaf]) == 1
	lst = [[1, total_nodes - 1]]

	@bootstrap
	def dfs(cur, prev):
		if g[cur] == [prev]:
			console('leaf', cur)
			yield 1
		desc = 1
		for nex in g[cur]:
			if nex != prev:
				val = (yield dfs(nex, cur))
				desc += val
				lst.append([total_nodes - val, val])
		yield desc
	dfs(g[starting_leaf][0], starting_leaf)
	console(lst)
	console(fact)
	lst = sorted([a * b for (a, b) in lst])[::-1]
	console(lst)
	res = 0
	for (a, b) in zip(lst, fact):
		res += a * b
		res = res % MOD
	return res % MOD

def console(*args):
	return
for case_num in range(int(input())):
	nrows = int(input())
	grid = []
	for _ in range(nrows - 1):
		grid.append(list(map(int, input().split())))
	_ = int(input())
	fact = list(map(int, input().split()))
	res = solve(grid, fact)
	print(res)


from types import GeneratorType
import sys

def bootstrap(f, stack=[]):

	def wrappedfunc(*args):
		if stack:
			return f(*args)
		else:
			to = f(*args)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def prod(a, M):
	ans = 1
	for ai in a:
		ans = ans * ai % M
	return ans

@bootstrap
def DFS(tree, node, leafs, visited):
	visited[node] = 1
	for child in tree[node]:
		if not visited[child]:
			l = (yield DFS(tree, child, leafs, visited))
			leafs[node] += leafs[child]
	leafs[node] += 1
	yield True

def main():
	M = 10 ** 9 + 7
	t = int(input())
	for _ in range(t):
		n = int(input())
		tree = [[] for i in range(n)]
		leafs = [0] * n
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			(u, v) = (u - 1, v - 1)
			tree[u].append(v)
			tree[v].append(u)
		visited = [0] * n
		DFS(tree, 0, leafs, visited)
		m = int(input())
		primes = list(map(int, input().split()))
		ans = 0
		leafs = [l * (n - l) for l in leafs[1:]]
		leafs.sort(reverse=True)
		primes.sort(reverse=True)
		if m > n - 1:
			x = m - n + 2
			primes = [prod(primes[:x], M)] + primes[x:]
			m = n
		for (i, l) in enumerate(leafs):
			if i < m:
				ans = (ans + primes[i] * l) % M
			else:
				ans = (ans + l) % M
		print(ans)
FIO = 10
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import os
BUFSIZE = 1024 * 8

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline

def dfs(tree, root):
	n = len(tree)
	visited = [False] * n
	visited[root] = True
	tp_sorted = [root]
	stack = [root]
	while stack:
		new_stack = []
		for v in stack:
			for nxt_v in tree[v]:
				if visited[nxt_v]:
					continue
				visited[nxt_v] = True
				new_stack.append(nxt_v)
				P[nxt_v] = v
				tp_sorted.append(nxt_v)
		stack = list(new_stack)
	return (tp_sorted, P)
t = int(input())
for _ in range(t):
	n = int(input())
	edges = [list(map(int, input().split())) for i in range(n - 1)]
	tree = [[] for i in range(n)]
	for (a, b) in edges:
		a -= 1
		b -= 1
		tree[a].append(b)
		tree[b].append(a)
	root = 0
	P = [-1] * n
	(tp_sort, P) = dfs(tree, root)
	W = [0] * n
	tp_sort = tp_sort[::-1]
	for v in tp_sort:
		if P[v] != -1:
			W[P[v]] += W[v] + 1
	m = int(input())
	primes = list(map(int, input().split()))
	primes.sort(reverse=True)
	for i in range(n):
		W[i] += 1
		W[i] = W[i] * (n - W[i])
	W.sort(reverse=True)
	if len(primes) > n - 1:
		mul = 1
		for i in range(len(primes) - n + 2):
			mul *= primes[i]
			mul = mul % (10 ** 9 + 7)
		primes = [mul] + primes[len(primes) - n + 2:]
	while len(primes) < n - 1:
		primes.append(1)
	ans = 0
	for i in range(n - 1):
		ans += W[i] * primes[i] % (10 ** 9 + 7)
	print(ans % (10 ** 9 + 7))


import sys
inp = sys.stdin.buffer.readline
inar = lambda : list(map(int, inp().split()))
inin = lambda : int(inp())
inst = lambda : inp().decode().strip()
wrt = sys.stdout.write
pr = lambda *args, end='\n': wrt(' '.join([str(x) for x in args]) + end)
enum = enumerate
inf = float('inf')
cdiv = lambda x, y: -(-x // y)
mod = 1000000007

def DFS(gr, cost):
	n = len(gr)
	vis = [False for i in range(n)]
	fin = [False for i in range(n)]
	dp = [None for i in range(n)]
	ans = 0

	def dfs(node):
		stack = [node]
		while stack:
			node = stack[-1]
			if not vis[node]:
				vis[node] = True
				for i in gr[node]:
					if not vis[i]:
						stack.append(i)
			else:
				stack.pop()
				dp[node] = 1
				for i in gr[node]:
					if fin[i]:
						dp[node] += dp[i]
						cost.append(dp[i] * (n - 1 - dp[i]))
				fin[node] = True
		return dp[node]
	for i in range(n):
		if not vis[i]:
			ans += dfs(i)
	return ans
_T_ = inin()
for _t_ in range(_T_):
	n = inin()
	gr = [[] for i in range(n + 1)]
	childs = [1 for i in range(n + 1)]
	cost = []
	for _ in range(n - 1):
		(u, v) = inar()
		gr[u].append(v)
		gr[v].append(u)
	m = inin()
	cm = inar()
	cm.sort()
	DFS(gr, cost)
	cost.sort()
	ll = len(cost)
	if ll >= m:
		cm = [1 for i in range(ll - m)] + cm
	else:
		while len(cm) != ll:
			cm[-2] *= cm[-1]
			cm[-2] %= mod
			cm.pop()
	s = 0
	for i in range(ll):
		s += cm[i] % mod * (cost[i] % mod) % mod
		s %= mod
	print(s)


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	n = int(input())
	edge = [[] for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		edge[u].append(v)
		edge[v].append(u)
	m = int(input())
	pf = [int(item) for item in input().split()]
	st = []
	weight = [1] * n
	cost = []
	st.append((-1, 0, True))
	while st:
		(p, v, is_decreasing) = st.pop()
		if is_decreasing:
			if p != -1:
				st.append((v, p, False))
			for nv in edge[v]:
				if nv == p:
					continue
				st.append((v, nv, True))
		else:
			cost.append(weight[p] * (n - weight[p]))
			weight[v] += weight[p]
	cost.sort()
	pf.sort()
	ret = 0
	if len(pf) > len(cost):
		accum = 1
		for _ in range(len(pf) - len(cost)):
			accum *= pf.pop()
			accum %= MOD
		pf[-1] *= accum
	pf.reverse()
	for item in pf:
		ret += item * cost.pop()
		ret %= MOD
	ret += sum(cost)
	print(ret % MOD)


from collections import defaultdict, deque
from sys import stdin
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	adj = defaultdict(set)
	for i in range(n - 1):
		(x, y) = map(int, stdin.readline().split())
		x -= 1
		y -= 1
		adj[x].add(y)
		adj[y].add(x)
	m = int(input())
	k = list(map(int, stdin.readline().split()))
	k.sort()
	q = deque()
	for x in adj:
		if len(adj[x]) == 1:
			q.append(x)
	count = [1] * n
	while len(q) > 1:
		u = q.popleft()
		baap = adj[u].pop()
		count[baap] += count[u]
		adj[baap].remove(u)
		if len(adj[baap]) == 1:
			q.append(baap)
	for (i, j) in enumerate(count):
		count[i] = j * (n - j)
	count.sort()
	count = count[1:]
	if m < n - 1:
		k = [1] * (n - 1 - m) + k
	elif m > n - 1:
		t = 1
		for i in range(n - 2, m):
			t = t * k[i] % mod
		k = k[:n - 2] + [t]
	res = 0
	for i in range(n - 1):
		res += count[i] * k[i] % mod
	print(res % mod)


import sys
inp = sys.stdin.buffer.readline
inar = lambda : list(map(int, inp().split()))
inin = lambda : int(inp())
inst = lambda : inp().decode().strip()
mod = 1000000007

def DFS(gr, cost):
	n = len(gr)
	vis = [False for i in range(n)]
	fin = [False for i in range(n)]
	dp = [None for i in range(n)]
	ans = 0

	def dfs(node):
		stack = [node]
		while stack:
			node = stack[-1]
			if not vis[node]:
				vis[node] = True
				for i in gr[node]:
					if not vis[i]:
						stack.append(i)
			else:
				stack.pop()
				dp[node] = 1
				for i in gr[node]:
					if fin[i]:
						dp[node] += dp[i]
						cost.append(dp[i] * (n - dp[i]))
				fin[node] = True
	for i in range(n):
		if not vis[i]:
			dfs(i)
_T_ = inin()
for _t_ in range(_T_):
	n = inin()
	gr = [[] for i in range(n)]
	cost = []
	for _ in range(n - 1):
		(u, v) = inar()
		gr[u - 1].append(v - 1)
		gr[v - 1].append(u - 1)
	m = inin()
	cm = inar()
	cm.sort()
	DFS(gr, cost)
	cost.sort()
	ll = len(cost)
	if ll >= m:
		cm = [1 for i in range(ll - m)] + cm
	else:
		while len(cm) != ll:
			cm[-2] *= cm[-1]
			cm[-2] %= mod
			cm.pop()
	s = 0
	for i in range(ll):
		s += cm[i] % mod * (cost[i] % mod) % mod
		s %= mod
	print(s)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

@iterative
def dfs(v, visited, st, new, ans, help):
	new.append(st)
	visited[st] = 1
	for i in v[st]:
		if visited[i] == 0:
			ok = (yield dfs(v, visited, i, new, ans, help))
			ans[st] += ans[i] + 1
			help.append((ans[i] + 1) * (len(v) - ans[i] - 1))
	yield True

def solve():
	n = int(inp())
	g = [[] for i in range(n)]
	for i in range(n - 1):
		(a, b) = sep()
		a -= 1
		b -= 1
		g[a].append(b)
		g[b].append(a)
	ans = [0] * n
	visited = [0] * n
	new = []
	help = []
	dfs(g, visited, 0, new, ans, help)
	m = int(inp())
	a = lis()
	help = sorted(help)[::-1]
	if m < n - 1:
		while len(a) != n - 1:
			a.append(1)
	a = sorted(a)[::-1]
	ans = [0] * (n - 1)
	temp = 1
	for i in range(len(a) - (n - 2)):
		temp *= a[i]
		temp %= mod
	ans[0] += help[0] * temp
	ans[0] %= mod
	for i in range(len(a) - (n - 2), len(a)):
		ans[i - (len(a) - (n - 2)) + 1] += help[i - (len(a) - (n - 2)) + 1] * a[i]
		ans[i - (len(a) - (n - 2)) + 1] %= mod
	print(sum(ans) % mod)
testcase(int(inp()))


import threading, sys
threading.stack_size(2 ** 26)
sys.setrecursionlimit(10 ** 6)

def main():
	t = int(input())
	for ii in range(t):
		n = int(input())
		tree = []
		for i in range(n):
			tree.append([])
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			u -= 1
			v -= 1
			tree[u].append(v)
			tree[v].append(u)
		m = int(input())
		primes = list(map(int, input().split()))
		primes.sort(reverse=True)
		freq = []
		visited = [-1] * n

		def dfs(node):
			visited[node] = 1
			ans = 0
			for i in tree[node]:
				if visited[i] == -1:
					ans += dfs(i)
			if node == 0:
				return 0
			ans += 1
			freq.append((n - ans) * ans)
			return ans
		dfs(0)
		final = 0
		mod = 10 ** 9 + 7
		freq.sort(reverse=True)
		i = 0
		if m < n:
			while i < n - 1:
				if i < m:
					final += freq[i] % mod * primes[i] % mod % mod
					final = final % mod
				else:
					final += freq[i] % mod
					final = final % mod
				i += 1
		else:
			first = 1
			for i in range(m - n + 2):
				first = first * primes[i] % mod % mod
			final = first * freq[0] % mod % mod
			start = m - n + 1
			for i in range(1, len(freq)):
				final += freq[i] % mod * primes[start + i] % mod % mod
				final = final % mod
		print(final)
threading.Thread(target=main).start()


import sys
input = sys.stdin.buffer.readline
inin = lambda : int(input())
inar = lambda : list(map(int, input().split()))
inst = lambda : input().decode().rstrip('\n\r')
from types import GeneratorType

def recursive(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
gr = []
childs = []
n = 0

@recursive
def dfs(node, par):
	global gr, cost, n, childs
	su = 1
	for i in gr[node]:
		if i != par:
			yield dfs(i, node)
			su += childs[i]
			cost.append(childs[i] * (n - childs[i]))
	childs[node] = su
	yield
mod = 1000000007
_T_ = inin()
for _t_ in range(_T_):
	n = inin()
	gr = [[] for i in range(n + 1)]
	childs = [1 for i in range(n + 1)]
	cost = []
	for _ in range(n - 1):
		(u, v) = inar()
		gr[u].append(v)
		gr[v].append(u)
	m = inin()
	cm = inar()
	cm.sort()
	dfs(1, 0)
	cost.sort()
	ll = len(cost)
	if ll >= m:
		cm = [1 for i in range(ll - m)] + cm
	else:
		while len(cm) != ll:
			cm[-2] *= cm[-1]
			cm[-2] %= mod
			cm.pop()
	s = 0
	for i in range(ll):
		s += cm[i] % mod * (cost[i] % mod) % mod
		s %= mod
	print(s)


import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
q = int(input())
res = []
for _ in range(q):
	n = int(input())
	E = [[] for _ in range(n + 1)]
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		E[x].append(y)
		E[y].append(x)
	m = int(input())
	V = sorted(map(int, input().split()))
	if m < n - 1:
		V = [1] * (n - 1 - m) + V
	else:
		X = 1
		for j in range(m - n + 1):
			X = X * V[-j - 1] % mod
		V[n - 2] = V[n - 2] * X % mod
	order = []
	que = [(1, -1)]
	par = [-1] * (n + 1)
	size = [1] * (n + 1)
	while que:
		(x, px) = que.pop()
		order.append(x)
		for v in E[x]:
			if v == px:
				continue
			que.append((v, x))
			par[v] = x
	products = []
	order.reverse()
	for x in order:
		px = par[x]
		if px == -1:
			continue
		products.append(size[x] * (n - size[x]))
		size[px] += size[x]
	products.sort()
	ans = 0
	for i in range(n - 1):
		ans = (ans + products[i] * V[i]) % mod
	res.append(ans)
print('\n'.join(map(str, res)))


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	n = int(input())
	adj_lis = []
	adj_cnt = []
	for _ in range(n):
		adj_lis.append([])
		adj_cnt.append(0)
	adj_cnt[0] = 1
	par = [-1] * n
	des_cnt = [1] * n
	leaf_q = []
	edgeNumber = []
	for _ in range(n - 1):
		(p, q) = map(int, input().split())
		adj_lis[p - 1].append(q - 1)
		adj_lis[q - 1].append(p - 1)
		adj_cnt[p - 1] += 1
		adj_cnt[q - 1] += 1
	treeStack = [(0, -1)]
	while treeStack:
		(v, par_v) = treeStack.pop()
		par[v] = par_v
		for x in adj_lis[v]:
			if x != par_v:
				treeStack.append((x, v))
		if adj_cnt[v] == 1:
			leaf_q.append(v)
	while leaf_q:
		x = leaf_q.pop()
		if x == 0:
			continue
		edgeNumber.append(des_cnt[x] * (n - des_cnt[x]))
		des_cnt[par[x]] += des_cnt[x]
		adj_cnt[par[x]] -= 1
		if adj_cnt[par[x]] == 1:
			leaf_q.append(par[x])
	edgeNumber.sort()
	m = int(input())
	edgeWeight = []
	primeList = list(map(int, input().split()))
	primeList.sort()
	if n - 1 < m:
		for i in range(n - 1):
			edgeWeight.append(primeList[i])
		for i in range(n - 1, m):
			edgeWeight[n - 2] *= primeList[i]
			edgeWeight[n - 2] %= MOD
	else:
		for i in range(n - 1 - m):
			edgeWeight.append(1)
		for i in range(m):
			edgeWeight.append(primeList[i])
	ans = 0
	for i in range(n - 1):
		ans += edgeNumber[i] * edgeWeight[i]
		ans %= MOD
	print(ans)


mod = 10 ** 9 + 7
import sys
input = sys.stdin.readline
from collections import deque

class Graph(object):

	def __init__(self, n, d):
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self, x, y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root):
		queue = [root]
		queue = deque(queue)
		vis = [0] * self.n
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i] == 0:
					queue.append(i)
					self.parent[i] = element
					vis[i] = 1

	def dfs(self, root, ans):
		stack = [root]
		vis = [0] * self.n
		stack2 = []
		while len(stack) != 0:
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i] == 0:
					self.parent[i] = element
					stack.append(i)
		while len(stack2) != 0:
			element = stack2.pop()
			m = 0
			for i in self.graph[element]:
				if i != self.parent[element]:
					m += ans[i]
			ans[element] = m + 1
		return ans

	def shortestpath(self, source, dest):
		self.bfs(source)
		path = [dest]
		while self.parent[path[-1]] != -1:
			path.append(parent[path[-1]])
		return path[::-1]

	def detect_cycle(self):
		indeg = [0] * self.n
		for i in range(self.n):
			for j in self.graph[i]:
				indeg[j] += 1
		q = deque()
		vis = 0
		for i in range(self.n):
			if indeg[i] == 0:
				q.append(i)
		while len(q) != 0:
			e = q.popleft()
			vis += 1
			for i in self.graph[e]:
				indeg[i] -= 1
				if indeg[i] == 0:
					q.append(i)
		if vis != self.n:
			return True
		return False

	def reroot(self, root, ans):
		stack = [root]
		vis = [0] * n
		while len(stack) != 0:
			e = stack[-1]
			if vis[e]:
				stack.pop()
				continue
			vis[e] = 1
			for i in graph[e]:
				if not vis[e]:
					stack.append(i)
			if self.parent[e] == -1:
				continue

	def maximizeSum(self):
		edges = []
		for i in range(1, n):
			edges.append(count[i] * (n - count[i]))
		edges.sort()
		ans = 0
		for i in range(n - 1):
			ans += edges[i] * a[i] % mod
			ans = ans % mod
		return ans
for nt in range(int(input())):
	n = int(input())
	g = Graph(n, False)
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		g.addEdge(x - 1, y - 1)
	m = int(input())
	a = list(map(int, input().split()))
	if m <= n - 1:
		a.extend([1] * (n - 1 - m))
		a.sort()
	else:
		a.sort()
		x = 1
		for i in range(n - 2, m):
			x = x * a[i] % mod
			x = x % mod
		a = a[0:n - 2] + [x]
	count = [0] * n
	count = g.dfs(0, count)
	print(g.maximizeSum())


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
from copy import deepcopy
from itertools import chain

def to_1d(iterable):
	return list(chain(*iterable))

def to_tree(graph, root=0):
	graph[:] = map(set, graph)
	stack = [[root]]
	while stack:
		if not stack[-1]:
			del stack[-1]
			continue
		vertex = stack[-1].pop()
		for e in graph[vertex]:
			graph[e].remove(vertex)
		stack.append(list(graph[vertex]))
	graph[:] = map(list, graph)

def to_graph(tree, to_list=False):
	tree[:] = map(set, tree)
	for (node1, node_set) in enumerate(deepcopy(tree)):
		for node2 in node_set:
			tree[node2].add(node1)
	if to_list:
		tree[:] = map(list, tree)

def tree_bfs(tree, start=0, flat=False) -> list:
	stack = [start]
	result = []
	while stack:
		new_stack = []
		if flat:
			result.extend(stack)
		else:
			result.append(stack)
		for node in stack:
			new_stack.extend(tree[node])
		stack = new_stack
	return result

def tree_postorder(tree, root=0, flat=False):
	return tree_bfs(tree, root, flat=flat)[::-1]

def tree_edge_descendant(tree, edge_time_count=False, root=0):
	vertices = len(tree)
	graph = deepcopy(tree)
	to_graph(graph)
	results = [[] for _ in range(vertices)]
	for leaves in tree_postorder(tree)[:-1]:
		for leaf in leaves:
			graph[leaf] = list(graph[leaf])
			graph[graph[leaf][0]].remove(leaf)
		for leaf in leaves:
			children = sum(results[leaf]) + 1
			results[graph[leaf][0]].append(children)
	if edge_time_count:
		for result in results:
			result[:] = map(lambda x: x * (vertices - x), result)
	return results
from functools import reduce
MOD = int(1000000000.0) + 7
g = []
for __ in range(itg()):
	n = itg()
	g = [list() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = mpint()
		g[u - 1].append(v - 1)
		g[v - 1].append(u - 1)
	to_tree(g)
	m = itg()
	factors = sorted(mpint())
	count = tree_edge_descendant(g, True)
	n -= 1
	if n >= m:
		factors = [1] * (n - m) + factors
	else:
		while len(factors) != n:
			factors[-1] = factors[-2] * factors.pop() % MOD
	count = sorted(to_1d(count))
	print(reduce(lambda a, b: (a + b) % MOD, (time * value % MOD for (time, value) in zip(count, factors)), 0))


import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
t = int(input())
for tests in range(t):
	n = int(input())
	E = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		E[x].append(y)
		E[y].append(x)
	m = int(input())
	V = sorted(map(int, input().split()))
	if m <= n - 1:
		V = [1] * (n - 1 - m) + V
	else:
		X = 1
		for j in range(m - n + 1):
			X = X * V[-j - 1] % mod
		V[n - 2] = V[n - 2] * X % mod
	TOP_SORT = []
	Q = [1]
	USE = [0] * (n + 1)
	USE[1] = 1
	P = [-1] * (n + 1)
	while Q:
		x = Q.pop()
		TOP_SORT.append(x)
		for to in E[x]:
			if USE[to] == 0:
				Q.append(to)
				P[to] = x
				USE[to] = 1
	L = [1] * (n + 1)
	LIST = []
	for x in TOP_SORT[1:][::-1]:
		LIST.append(L[x] * (n - L[x]))
		L[P[x]] += L[x]
	LIST.sort()
	ANS = 0
	for i in range(n - 1):
		ANS = (ANS + LIST[i] * V[i]) % mod
	print(ANS)


import io, os
from collections import deque
import bisect
RL = lambda : list(map(int, input().split(' ')))

def Levels(graph, V):
	level = [None] * V
	dfs = []
	st = [0]
	while st:
		node = st.pop()
		dfs.append(node)
		for child in graph[node]:
			if child == par[node]:
				continue
			par[child] = node
			st.append(child)
	return dfs
m = 10 ** 9 + 7

def addEdge(a, b):
	global adj
	adj[a].append(b)
	adj[b].append(a)
T = int(input())
for _ in range(T):
	N = int(input())
	count1 = [1] * N
	par = [-1] * N
	adj = [[] for i in range(N)]
	for i in range(N - 1):
		(x, y) = map(int, input().split())
		addEdge(x - 1, y - 1)
	pp = int(input())
	primes = RL()
	dfs = Levels(adj, N)
	for b in dfs[::-1]:
		if b == 0:
			break
		count1[par[b]] += count1[b]
	ma = []
	for i in range(N):
		ma.append((N - count1[i]) * count1[i])
	ma.sort(reverse=True)
	primes.sort(reverse=True)
	ans = 0
	for i in range(1, max(0, len(primes) - (N - 1)) + 1):
		primes[0] = primes[0] % m * (primes[i] % m) % m
		primes[i] = 0
	primes.sort(reverse=True)
	for i in range(len(ma)):
		if i >= len(primes):
			ans = (ans % m + ma[i] % m) % m
		else:
			ans = (ans % m + ma[i] % m * (primes[i] % m) % m) % m
	print(ans % m)


import sys
(_ord, inp, num, neg, _Index) = (lambda x: x, [], 0, False, 0)
(i, s) = (0, sys.stdin.buffer.read())
try:
	while True:
		if s[i] >= b'0'[0]:
			num = 10 * num + _ord(s[i]) - 48
		elif s[i] == b'-'[0]:
			neg = True
		elif s[i] != b'\r'[0]:
			inp.append(-num if neg else num)
			(num, neg) = (0, False)
		i += 1
except IndexError:
	pass
if s and s[-1] >= b'0'[0]:
	inp.append(-num if neg else num)

def fin(size=None):
	global _Index
	if size == None:
		ni = _Index
		_Index += 1
		return inp[ni]
	else:
		ni = _Index
		_Index += size
		return inp[ni:ni + size]
mod = 1000000007

def DFS(gr, cost):
	n = len(gr)
	vis = [False for i in range(n)]
	fin = [False for i in range(n)]
	dp = [None for i in range(n)]
	ans = 0

	def dfs(node):
		stack = [node]
		while stack:
			node = stack[-1]
			if not vis[node]:
				vis[node] = True
				for i in gr[node]:
					if not vis[i]:
						stack.append(i)
			else:
				stack.pop()
				dp[node] = 1
				for i in gr[node]:
					if fin[i]:
						dp[node] += dp[i]
						cost.append(dp[i] * (n - 1 - dp[i]))
				fin[node] = True
		return dp[node]
	for i in range(n):
		if not vis[i]:
			ans += dfs(i)
	return ans
_T_ = fin()
for _t_ in range(_T_):
	n = fin()
	gr = [[] for i in range(n + 1)]
	childs = [1 for i in range(n + 1)]
	cost = []
	for _ in range(n - 1):
		(u, v) = fin(2)
		gr[u].append(v)
		gr[v].append(u)
	m = fin()
	cm = fin(m)
	cm.sort()
	DFS(gr, cost)
	cost.sort()
	ll = len(cost)
	if ll >= m:
		cm = [1 for i in range(ll - m)] + cm
	else:
		while len(cm) != ll:
			cm[-2] *= cm[-1]
			cm[-2] %= mod
			cm.pop()
	s = 0
	for i in range(ll):
		s += cm[i] % mod * (cost[i] % mod) % mod
		s %= mod
	print(s)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from collections import defaultdict as dc
M = 1000000007
for _ in range(N()):
	n = N()
	dic = dc(list)
	cn = [1] * (n + 1)
	gress = [0] * (n + 1)
	for _ in range(n - 1):
		(u, v) = RL()
		dic[u].append(v)
		dic[v].append(u)
		gress[u] += 1
		gress[v] += 1
	now = set()
	for i in range(1, n + 1):
		if gress[i] == 1:
			now.add(i)
	while now:
		node = now.pop()
		gress[node] = 0
		for t in dic[node]:
			if gress[t] > 0:
				cn[t] += cn[node]
				gress[t] -= 1
				if gress[t] == 1:
					now.add(t)
	for i in range(1, n + 1):
		cn[i] = cn[i] * (n - cn[i])
	cn.sort()
	cn = cn[-(n - 1):]
	m = N()
	p = RLL()
	p.sort()
	if m > n - 1:
		tmp = 1
		for t in p[n - 2:]:
			tmp = tmp * t % M
		p = p[:n - 2] + [tmp]
	else:
		p = [1] * (n - 1 - m) + p
	res = 0
	for i in range(n - 1):
		res += cn[i] * p[i] % M
	print(res % M)


from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
import sys, math
input = sys.stdin.readline
t = int(input())
mod = 10 ** 9 + 7
count1 = None

@bootstrap
def numberOfNodes(s, e):
	count1[s] = 1
	for u in graph[s]:
		if u == e:
			continue
		yield numberOfNodes(u, s)
		count1[s] += count1[u]
	yield
for r in range(t):
	n = int(input())
	graph = []
	edges = []
	for i in range(n):
		graph.append([])
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		graph[u].append(v)
		graph[v].append(u)
		edges.append([u, v])
	m = int(input())
	p = list(map(int, input().split()))
	count1 = [0] * n
	numberOfNodes(0, -1)
	edgesFrequency = []
	for i in range(1, n):
		edgesFrequency.append(count1[i] * (n - count1[i]))
	p.sort(reverse=True)
	edgesFrequency.sort(reverse=True)
	if n - 1 > m:
		diff = n - 1 - m
		for i in range(diff):
			p.append(1)
	elif m > n - 1:
		diff = m - (n - 1)
		temp = 1
		for i in range(diff + 1):
			temp *= p[i]
			temp %= mod
		temp2 = [temp]
		for i in range(diff + 1, m):
			temp2.append(p[i])
		p = temp2
	ans = 0
	for i in range(n - 1):
		ans += edgesFrequency[i] * p[i] % mod
		ans %= mod
	print(ans)


import sys
q = 10 ** 9 + 7
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	n = int(sys.stdin.readline().strip())
	N = [[] for i in range(0, n)]
	D = [0] * n
	for i in range(0, n - 1):
		(u, v) = list(map(int, sys.stdin.readline().strip().split()))
		(u, v) = (u - 1, v - 1)
		N[u].append(v)
		N[v].append(u)
		D[u] = D[u] + 1
		D[v] = D[v] + 1
	m = int(sys.stdin.readline().strip())
	p = list(map(int, sys.stdin.readline().strip().split()))
	F = []
	M = [1] * n
	L = [i for i in range(0, n)]
	while len(L) > 0:
		L2 = []
		i = 0
		while i < len(L):
			u = L[i]
			while D[u] == 1:
				F.append(M[u] * (n - M[u]))
				D[u] = -1
				for v in N[u]:
					if D[v] != -1:
						D[v] = D[v] - 1
						M[v] = M[v] + M[u]
						if D[v] == 1:
							u = v
			if D[L[i]] > 1:
				L2.append(i)
			i = i + 1
		L = L2[:]
	p.sort()
	F.sort()
	ans = 0
	if m <= n - 1:
		p = [1] * (n - 1 - m) + p
	else:
		for i in range(n - 1, m):
			p[n - 2] = p[n - 2] * p[i] % q
	for i in range(0, n - 1):
		ans = (ans + p[i] * F[i]) % q
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def solve():
	n = N()
	g = [[] for _ in range(n + 1)]
	for i in range(n - 1):
		(a, b) = sep()
		a -= 1
		b -= 1
		g[a].append(b)
		g[b].append(a)
	m = N()
	ar = lis()
	ar.sort()
	dp = [0] * (n + 1)

	@iterative
	def dfs(v, p):
		if len(g[v]) == 1 and g[v][0] == p:
			dp[v] = 1
			yield
		dp[v] = 1
		for c in g[v]:
			if c == p:
				continue
			yield dfs(c, v)
			dp[v] += dp[c]
		yield
	dfs(0, 0)
	temp = []
	for i in range(1, n):
		temp.append(dp[i] * (n - dp[i]))
	temp.sort()
	if m > n - 1:
		p = 1
		t = m - n + 1
		for i in range(t):
			p = p * ar.pop() % mod
		ar[-1] = ar[-1] * p % mod
	else:
		ar = [1] * (n - 1 - m) + ar
	ans = 0
	for i in range(n - 1):
		ans += temp[i] * ar[i]
		ans %= mod
	print(ans)
testcase(int(inp()))


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
ans = 0

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		n = inp()
		grid = [{} for i in range(n + 1)]
		for i in range(n - 1):
			[a, b] = inlt()
			grid[a][b] = 1
			grid[b][a] = 1
		m = inp()
		p = inlt()
		p.sort(reverse=True)
		if m > n - 1:
			d = 1
			for i in range(m - n + 2):
				a = p.pop(0)
				d = d * a % mod
			p = [d] + p
		m = len(p)
		parent = [0 for i in range(n + 1)]
		nodes = [0 for i in range(n + 1)]
		times = []
		queue = [1]
		done = [0 for i in range(n + 1)]
		done[1] = 1
		while queue != []:
			curr = queue[-1]
			flag = 0
			for i in grid[curr]:
				if i != parent[curr]:
					if curr in grid[i]:
						del grid[i][curr]
					parent[i] = curr
				if done[i] == 0:
					done[i] = 1
					flag = 1
					queue.append(i)
			if flag == 1:
				continue
			curr = queue.pop()
			reach = 1
			for i in grid[curr]:
				up = (n - nodes[i]) * nodes[i]
				times.append(up)
				reach = reach + nodes[i]
			nodes[curr] = reach
		times.sort(reverse=True)
		ans = 0
		for i in range(len(times)):
			if i < m:
				ans = (ans + times[i] * p[i]) % mod
			else:
				ans = (ans + times[i] * 1) % mod
		print(ans)
main()


import sys
input = sys.stdin.readline
mod = 1000000007
for f in range(int(input())):
	n = int(input())
	neig = [0] * n
	for i in range(n):
		neig[i] = [0]
	edges = []
	for i in range(n - 1):
		(vertexa, vertexb) = map(int, input().split())
		vertexa -= 1
		vertexb -= 1
		neig[vertexa][0] += 1
		neig[vertexb][0] += 1
		neig[vertexa].append(vertexb)
		neig[vertexb].append(vertexa)
		edges.append([vertexa, vertexb])
	tod = []
	upn = [-1] * n
	dn = [1] * n
	for i in range(n):
		if neig[i][0] == 1:
			tod.append(i)
	while len(tod) > 0:
		x = tod.pop()
		neig[x][0] = 0
		for foo in range(1, len(neig[x])):
			v = neig[x][foo]
			if neig[v][0] > 0:
				neig[v][0] -= 1
				upn[x] = v
				dn[v] += dn[x]
				if neig[v][0] == 1:
					tod.append(v)
	m = int(input())
	p = list(map(int, input().split()))
	p.sort(reverse=True)
	facs = [1] * (n - 1)
	if m < n:
		for i in range(m):
			facs[i] = p[i]
	else:
		diff = m - (n - 1)
		for j in range(diff):
			facs[0] *= p[j]
			facs[0] %= mod
		for j in range(diff, m):
			facs[j - diff] *= p[j]
	wedgies = [0] * (n - 1)
	for i in range(n - 1):
		(a, b) = (edges[i][0], edges[i][1])
		if upn[a] == b:
			wedgies[i] = dn[a] * (n - dn[a])
		else:
			wedgies[i] = dn[b] * (n - dn[b])
	wedgies.sort(reverse=True)
	sol = 0
	for i in range(n - 1):
		sol += wedgies[i] * facs[i]
		sol %= mod
	print(sol)


for t in range(int(input())):
	n = int(input())
	d = {}
	children = {}
	for i in range(n):
		d[i] = set()
	for i in range(n):
		children[i] = 0
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		d[u - 1].add(v - 1)
		d[v - 1].add(u - 1)
	child = []
	for i in d:
		if i != 0 and len(d[i]) == 1:
			child.append(i)
	p1 = []
	still = n - 1
	while still != 0:
		still -= 1
		i = child.pop()
		p1.append(children[i])
		par = d[i].pop()
		children[par] += 1 + children[i]
		d[par].remove(i)
		if len(d[par]) == 1 and par != 0:
			child.append(par)
	m1 = []
	for i in p1:
		m1.append((i + 1) * (n - i - 1))
	m1 = list(sorted(m1))[::-1]
	m = int(input())
	lm = list(map(int, input().split()))
	while len(lm) < n - 1:
		lm.append(1)
	lm = list(sorted(lm))
	while len(lm) > n - 1:
		new = lm[-1] * lm[-2] % (10 ** 9 + 7)
		lm.pop()
		lm[-1] = new
	ans = 0
	for i in range(n - 1):
		ans += lm[i] * m1[n - 2 - i]
	print(ans % (10 ** 9 + 7))


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(N,) = map(int, input().split())
	d = [set() for _ in range(N + 1)]
	for i in range(N - 1):
		(u, v) = map(int, input().split())
		d[u].add((v, i))
		d[v].add((u, i))
	G = [set() for _ in range(N + 1)]
	stack = [2]
	vs = set([2])
	vs_dfs = list()
	while stack:
		v = stack.pop()
		vs_dfs.append(v)
		for (u, i) in d[v]:
			if u in vs:
				continue
			G[v].add((u, i))
			vs.add(u)
			stack.append(u)
	size = [0] * (N + 1)
	X = [0] * (N - 1)
	for v in vs_dfs[::-1]:
		tmp = 1
		for (u, i) in G[v]:
			tmp += size[u]
			X[i] = size[u] * (N - size[u])
		size[v] = tmp
	(M,) = map(int, input().split())
	P = list(map(int, input().split()))
	X.sort()
	X = X[::-1]
	mod = 10 ** 9 + 7
	if N - 1 >= M:
		P.sort()
		P = P[::-1]
		for _ in range(N - 1 - M):
			P.append(1)
	else:
		P.sort()
		for _ in range(M - (N - 1)):
			p = P.pop()
			P[-1] = P[-1] * p % mod
		P = P[::-1]
	R = 0
	for (x, p) in zip(X, P):
		R = (R + x * p) % mod
	print(R)


from sys import stdin
input = stdin.readline
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
dupa = None
nbr = None

@bootstrap
def dfs(v):
	dupa[v] = 1
	for w in nbr[v]:
		if dupa[w] == -1:
			chuj = (yield dfs(w))
			dupa[v] += chuj
	yield dupa[v]
q = int(input())
for _ in range(q):
	n = int(input())
	nbr = [[] for i in range(n)]
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		nbr[a - 1].append(b - 1)
		nbr[b - 1].append(a - 1)
	pier = int(input())
	p = list(map(int, input().split()))
	p.sort()
	p.reverse()
	dupa = [-1] * n
	dfs(0)
	actual = [dupa[i] * (n - dupa[i]) for i in range(1, n)]
	actual.sort()
	actual.reverse()
	if pier < n:
		p += [1] * (n - 1 - pier)
	else:
		p.reverse()
		while len(p) >= n:
			ddd = p.pop(-1)
			p[-1] = p[-1] * ddd % (10 ** 9 + 7)
		p.reverse()
	wyn = 0
	for i in range(n - 1):
		wyn += actual[i] * p[i]
	print(wyn % (10 ** 9 + 7))


from types import GeneratorType

def recursive(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('ascii')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())

def tree_edge_descendant(graph, edge_time_count=False, root=0):
	edges = len(graph) - 1
	descendant_count = []
	stack_par = [[root]]
	stack_val = [[0]]
	while len(descendant_count) != edges:
		if not stack_par[-1]:
			del stack_par[-1], stack_val[-1]
			value = stack_val[-1].pop() + 1
			descendant_count.append(value)
			stack_val[-2][-1] += value
			if not stack_val:
				del stack_val[-1]
			continue
		vertex = stack_par[-1].pop()
		stack_par.append(list(graph[vertex]))
		stack_val.append([0] * len(graph[vertex]))
	if edge_time_count:
		return list(map(lambda x: x * (len(graph) - x), descendant_count))
	return descendant_count

def to_tree(graph, root=0):
	graph[:] = map(set, graph)

	@recursive
	def dfs(v):
		for e in graph[v]:
			graph[e].remove(v)
			yield dfs(e)
		yield
	dfs(root)
	graph[:] = map(list, graph)
from functools import reduce
MOD = int(1000000000.0) + 7

def solve():
	g = []
	for __ in range(itg()):
		n = itg()
		g = [list() for _ in range(n)]
		for _ in range(n - 1):
			(u, v) = mpint()
			g[u - 1].append(v - 1)
			g[v - 1].append(u - 1)
		to_tree(g)
		m = itg()
		factors = sorted(mpint())
		count = sorted(tree_edge_descendant(g, True))
		n -= 1
		if n >= m:
			factors = [1] * (n - m) + factors
		else:
			while len(factors) != n:
				factors[-1] = factors[-2] * factors.pop() % MOD
		print(reduce(lambda a, b: (a + b) % MOD, (time * value % MOD for (time, value) in zip(count, factors)), 0))
solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	dic = {}
	dico = {}
	for i in range(1, n + 1):
		dic[i] = []
		dico[i] = []
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		dic[x].append(y)
		dic[y].append(x)
		dico[x].append(y)
		dico[y].append(x)
	dis = {}
	dis[1] = 0
	level = 1
	se = {1}
	ne = {1}
	while ne:
		tem = set({})
		for i in ne:
			xx = dic[i]
			for j in xx:
				if not j in se:
					se.add(j)
					dis[j] = level
					tem.add(j)
		ne = tem.copy()
		level += 1
	for i in dic:
		dic[i].sort(key=lambda x: dis[x])
	people = {}
	st = 1
	se = {1}
	people[1] = 1
	while dic[st]:
		ne = dic[st].pop()
		if not ne in se:
			people[ne] = 1
			se.add(ne)
		else:
			people[ne] += people[st]
		st = ne
	size = []
	se = {1}
	ne = {1}
	while ne:
		tem = set({})
		for i in ne:
			xx = dico[i]
			for j in xx:
				if not j in se:
					se.add(j)
					size.append(people[j] * (n - people[j]))
					tem.add(j)
		ne = tem.copy()
	size.sort(reverse=True)
	m = int(input())
	prime = list(map(int, input().split()))
	prime.sort(reverse=True)
	rem = 1000000007
	ans = 0
	if m <= n - 1:
		for i in range(m):
			ans = (ans + prime[i] * size[i] % rem) % rem
		for i in range(m, n - 1):
			ans = (ans % rem + size[i] % rem) % rem
	else:
		ext = m - (n - 1)
		for i in range(ext):
			prime[i + 1] = prime[i + 1] * prime[i] % rem
		for i in range(n - 1):
			ans = (ans + prime[i + ext] * size[i] % rem) % rem
	print(ans)


def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))

def dfs(adj, start=1):
	n = len(adj)
	visited = [False] * n
	euler = []
	srt = [start]
	parent = [-1] * n
	dp = [1] * n
	dp[0] = 0
	pv = 0
	while srt:
		v = srt.pop()
		if visited[v]:
			pv = euler[-1]
			dp[v] += dp[pv]
			euler.append(v)
			continue
		euler.append(v)
		visited[v] = True
		if parent[v] != -1:
			srt.append(parent[v])
		for u in adj[v]:
			if not visited[u]:
				parent[u] = v
				srt.append(u)
	return dp

def main():
	md = 10 ** 9 + 7
	T = iin()
	while T:
		T -= 1
		n = iin()
		adj = [[] for i in range(n + 1)]
		edge = {}
		for i in range(n - 1):
			(j, k) = lin()
			if j > k:
				(j, k) = (k, j)
			adj[j].append(k)
			adj[k].append(j)
			edge[j, k] = 1
		m = iin()
		p = lin()
		p.sort()
		dp = dfs(adj)
		ans = []
		for (i, j) in edge:
			mn = min(dp[i], dp[j])
			ans.append(mn * (n - mn))
		ans.sort()
		sol = [1] * (n - 1)
		st = 0
		pos = 0
		if m < n - 1:
			pos = n - 1 - m
		while st < m and pos < n - 1:
			sol[pos] = sol[pos] * p[st] % md
			st += 1
			pos += 1
		while st < m:
			sol[-1] = sol[-1] * p[st] % md
			st += 1
		sol1 = 0
		for i in range(n - 1):
			sol1 = (sol1 + ans[i] * sol[i] % md) % md
		print(sol1)
main()


import sys, threading

def rl():
	return [int(w) for w in sys.stdin.readline().split()]
MOD = 1000000007

def main():

	def walk(u, v):
		s = 1
		for i in adj[v]:
			if i != u:
				c = walk(v, i)
				w.append(c * (n - c))
				s += c
		return s
	for _ in range(rl()[0]):
		(n,) = rl()
		adj = [[] for _ in range(n + 1)]
		for i in range(1, n):
			(u, v) = rl()
			adj[u].append(v)
			adj[v].append(u)
		(m,) = rl()
		p = rl()
		while len(p) < n - 1:
			p.append(1)
		p.sort()
		w = []
		walk(0, 1)
		w.sort()
		r = 0
		for i in range(n - 2):
			r = (r + w[i] * p[i]) % MOD
		l = w[n - 2]
		for i in range(n - 2, max(m, n - 1)):
			l = l * p[i] % MOD
		r = (r + l) % MOD
		print(r)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


import sys
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2 ** 62 - 1

def read_int():
	return int(buff_readline())

def read_int_n():
	return list(map(int, buff_readline().split()))

def read_float():
	return float(buff_readline())

def read_float_n():
	return list(map(float, buff_readline().split()))

def read_str():
	return readline().strip()

def read_str_n():
	return readline().strip().split()

def error_print(*args):
	print(*args, file=sys.stderr)

def mt(f):
	import time

	def wrap(*args, **kwargs):
		s = time.time()
		ret = f(*args, **kwargs)
		e = time.time()
		error_print(e - s, 'sec')
		return ret
	return wrap
from collections import defaultdict, Counter

def slv(N, UV, M, P):
	g = defaultdict(list)
	for (u, v) in UV:
		g[u].append(v)
		g[v].append(u)
	np = Counter()
	s = [(u, -1)]
	o = []
	while s:
		(u, r) = s.pop()
		o.append((u, r))
		for v in g[u]:
			if v == r:
				continue
			s.append((v, u))
	o.reverse()
	cn = [0] * (N + 1)
	for (u, r) in o:
		n = 0
		vm = {}
		for v in g[u]:
			if v == r:
				continue
			n += cn[v]
			vm[v] = cn[v]
		cn[u] = n + 1
		for (v, m) in vm.items():
			np[min(u, v), max(u, v)] = (N - m) * m
	np = list(np.values())
	np.sort()
	P.sort()
	M = 10 ** 9 + 7
	while len(P) > len(np):
		p = P.pop()
		P[-1] *= p
		P[-1] %= M
	if len(P) < len(np):
		P = [1] * (len(np) - len(P)) + P
	ans = 0
	for (v, p) in zip(np, P):
		ans += v * p
		ans %= M
	return ans

def main():
	for _ in range(read_int()):
		N = read_int()
		UV = [read_int_n() for _ in range(N - 1)]
		M = read_int()
		P = read_int_n()
		print(slv(N, UV, M, P))
main()


from collections import deque
MOD = 1000000007
T = int(input())
for _ in range(T):
	n = int(input())
	e = [[] for _ in range(n + 1)]
	for _ in range(n - 1):
		(a, b) = map(int, input().split())
		e[a].append(b)
		e[b].append(a)
	m = int(input())
	p = list(sorted(map(int, input().split())))
	if m < n - 1:
		p = [1] * (n - 1 - m) + p
	else:
		tp = []
		for u in p:
			if len(tp) < n - 1:
				tp.append(u)
			else:
				tp[-1] = tp[-1] * u % MOD
		p = tp
	(q, par, order) = (deque([1]), [0] * (n + 1), [])
	while q:
		u = q.popleft()
		order.append(u)
		for v in e[u]:
			if v == par[u]:
				continue
			par[v] = u
			q.append(v)
	(lcc, ecc) = ([0] * (n + 1), [])
	for u in reversed(order):
		cc = 1
		for v in e[u]:
			if v == par[u]:
				continue
			cc += lcc[v]
		lcc[u] = cc
		if u != 1:
			ecc.append(cc * (n - cc))
	ecc.sort()
	res = 0
	for (u, v) in zip(p, ecc):
		res = (res + u * v) % MOD
	print(res)


from sys import stdin

def dfs(i):
	stack = []
	stack.append([i, []])
	while stack:
		(q, subs) = stack[-1]
		size = visited[q]
		if size == 0:
			visited[q] = size = 1
			subs[:] = [elem for elem in ed[q] if visited[elem] == 0]
		if subs:
			stack.append([subs.pop(), []])
		else:
			u = stack.pop()
			if stack:
				visited[stack[-1][0]] += size
t = int(input())
for g in range(t):
	n = int(input())
	visited = [0] * (n + 1)
	stack = []
	mod = 1000000007
	ed = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(a, b) = [int(q) for q in input().split()]
		ed[a].append(b)
		ed[b].append(a)
	m = int(input())
	f = [int(i) for i in input().split()]
	f.sort()
	dfs(1)
	if m > n - 1:
		for k in range(n - 1, m):
			f[n - 2] = f[n - 2] * f[k] % mod
			f[n - 2] %= mod
	else:
		f = [1] * (n - 1 - m) + f
	for i in range(n + 1):
		visited[i] = visited[i] * (n - visited[i])
	visited.sort()
	res = 0
	for i in range(n - 2, -1, -1):
		res += visited[i + 2] * f[i]
		res %= mod
	print(res)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import defaultdict, deque
t = int(input())
MOD = 10 ** 9 + 7
for _ in range(t):
	n = int(input())
	adj = defaultdict(list)
	edges_list = []
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		adj[u].append(v)
		adj[v].append(u)
		edges_list.append((u, v))
	m = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	size = [0] * (n + 1)
	parents = [0] * (n + 1)
	states = []
	q = deque([[1, -1]])
	while q:
		(e, p) = q.popleft()
		states.append(e)
		parents[e] = p
		for i in adj[e]:
			if i != p:
				q.append([i, e])
	for i in range(n, 0, -1):
		for j in adj[states[i - 1]]:
			if states[i - 1] == parents[j]:
				size[states[i - 1]] += 1 + size[j]
	weights = None
	if m >= n:
		first = a[0]
		second = deque(a[1:])
		while len(second) != n - 2:
			first = first * second.popleft() % MOD
		weights = [first] + list(second)
	else:
		weights = a.copy()
		while len(weights) != n - 1:
			weights.append(1)
	edge_bckt = []
	for i in edges_list:
		query = min(size[i[0]], size[i[1]])
		edge_bckt.append((query + 1) * (n - query - 1))
	edge_bckt.sort(reverse=True)
	prod = 0
	for i in range(len(edge_bckt)):
		prod = (prod + edge_bckt[i] * weights[i]) % MOD
	print(prod)


import sys
from collections import deque
t = int(input())
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 1000000007
for _ in range(t):

	class Graph:

		def __init__(self, V):
			self.V = V
			self.adj = [[] for i in range(V)]

		@bootstrap
		def DFSUtil(self, v):
			total = 1
			visited[v] = True
			for i in self.adj[v]:
				if visited[i] == False:
					count = (yield self.DFSUtil(i))
					weights.append(count * (n - count))
					total += count
			yield total

		def addEdge(self, v, w):
			self.adj[v].append(w)
			self.adj[w].append(v)
	weights = []
	n = int(input())
	G = Graph(n)
	for _ in range(n - 1):
		(u, v) = list(map(lambda x: int(x), input().split()))
		G.addEdge(u - 1, v - 1)
	visited = [False for _ in range(n)]
	G.DFSUtil(0)
	k = int(input())
	a = list(map(lambda x: int(x), input().split()))
	a.sort()
	leaf = 0
	for i in G.adj:
		if len(i) == 1:
			leaf += 1
	non_leaf = n - 1 - leaf
	if k < n - 1:
		a = [1] * (n - k - 1) + a
	if k > n - 1:
		ans = 1
		for i in range(n - 2, k):
			ans = ans % mod * a[i] % mod % mod
		a[n - 2] = ans
	ans = 0
	weights.sort()
	for i in range(0, n - 1):
		ans = (ans + weights[i] % mod * a[i] % mod % mod) % mod
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def dfs(graph, start=0):
	n = len(graph)
	dp = [0] * n
	(visited, finished) = ([False] * n, [False] * n)
	stack = [start]
	while stack:
		start = stack[-1]
		if not visited[start]:
			visited[start] = True
			for child in graph[start]:
				if not visited[child]:
					stack.append(child)
		else:
			stack.pop()
			dp[start] += 1
			for child in graph[start]:
				if finished[child]:
					dp[start] += dp[child]
			finished[start] = True
	return (visited, dp)
from collections import deque
for _ in range(int(input()) if True else 1):
	n = int(input())
	graph = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		graph[x] += [y]
		graph[y] += [x]
	(visited, dp) = dfs(graph, 1)
	x = dp[1:]
	x[0] -= 1
	for i in range(n):
		x[i] = x[i] * (n - x[i])
	x = sorted(x, reverse=True)
	m = int(input())
	p = deque(sorted(list(map(int, input().split())), reverse=True))
	while len(p) > n - 1:
		k = p.popleft()
		p[0] = p[0] * k % (10 ** 9 + 7)
	ans = 0
	mod = 10 ** 9 + 7
	for i in range(n - 1):
		if i < len(p):
			ans = (ans + x[i] * p[i]) % mod
		else:
			ans = (ans + x[i]) % mod
	print(ans)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def MI1():
	return map(int1, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
md = 10 ** 9 + 7
for _ in range(II()):
	n = II()
	to = [[] for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = MI1()
		to[u].append(v)
		to[v].append(u)
	m = II()
	pp = LI()
	ss = [0] * n
	cc = []
	stack = [(0, -1)]
	while stack:
		(u, pu) = stack.pop()
		if ss[u]:
			if pu != -1:
				ss[pu] += ss[u]
				cc.append(ss[u] * (n - ss[u]))
		else:
			ss[u] = 1
			stack.append((u, pu))
			for v in to[u]:
				if v == pu:
					continue
				stack.append((v, u))
	ans = 0
	cc.sort(reverse=True)
	pp.sort()
	while len(pp) > n - 1:
		p1 = pp.pop()
		p2 = pp.pop()
		pp.append(p1 * p2 % md)
	pp.reverse()
	pp += [1] * (len(cc) - len(pp))
	for (c, p) in zip(cc, pp):
		ans += c * p
		ans %= md
	print(ans)


import sys, threading

def main():

	def dfs(ver):
		if v[ver] == 1:
			return 0
		else:
			v[ver] = 1
			res = 1
			for w in adj[ver]:
				if v[w] == 0:
					res += dfs(w)
			if ver != 1:
				ans.append(res * (n - res))
			return res
	re = 10 ** 9 + 7
	t = int(input())
	for i in range(t):
		n = int(input())
		adj = [[] for j in range(n + 1)]
		for j in range(n - 1):
			(u, v) = map(int, input().split())
			adj[u].append(v)
			adj[v].append(u)
		m = int(input())
		p = list(map(int, input().split()))
		p.sort()
		v = [0] * (n + 1)
		ans = []
		dfs(1)
		ans.sort()
		s = 0
		if n - 1 >= m:
			p.reverse()
			ans.reverse()
			j = 0
			while j < m:
				s = (s + ans[j] * p[j]) % re
				j += 1
			while j < n - 1:
				s = (s + ans[j]) % re
				j += 1
		else:
			z = m - 1
			q = 1
			while z >= n - 2:
				q = p[z] * q % re
				z += -1
			s = (s + q * ans[-1]) % re
			j = n - 3
			while j >= 0:
				s = (s + ans[j] * p[j]) % re
				j += -1
		print(s % re)
sys.setrecursionlimit(2 * 10 ** 5)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()


from collections import defaultdict
mod = 10 ** 9 + 7

def dfs(node):
	ch = defaultdict(lambda : 1)
	stack = [node]
	visited = [0 for i in range(n + 1)]
	visited[node] = 1
	for i in stack:
		for j in tree[i]:
			if not visited[j]:
				visited[j] = i
				stack.append(j)
	while len(stack) > 1:
		nxt = stack.pop()
		ch[visited[nxt]] += ch[nxt]
	return sorted(ch.values())
for _ in range(int(input())):
	n = int(input())
	tree = defaultdict(list)
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		tree[u].append(v)
		tree[v].append(u)
	children = dfs(1)
	k = int(input())
	primes = sorted(map(int, input().split()))
	for i in range(k - (n - 1)):
		curr = primes.pop()
		primes[-1] = curr * primes[-1] % mod
	primes = [1] * max(n - 1 - k, 0) + primes
	passage = []
	for i in range(n - 1):
		passage.append(children[i] * (n - children[i]))
	passage.sort()
	ans = 0
	for (i, j) in zip(primes, passage):
		ans += i * j
		ans = ans % mod
	print(ans % mod)


import sys, math, threading, heapq
sys.setrecursionlimit(10 ** 7)
threading.stack_size(10 ** 8)

def solve():

	def get_int():
		return list(map(int, sys.stdin.readline().strip().split()))

	def dfs(adj_list, imp_edges, v_list, n, u=1):
		child = 1
		for v in adj_list[u]:
			if v_list[v] == False:
				v_list[v] = True
				x = dfs(adj_list, imp_edges, v_list, n, v)
				heapq.heappush(imp_edges, (-(x * (n - x)), u, v))
				child += x
		return child
	if __name__ == '__main__':
		t = int(input())
		mod = 10 ** 9 + 7
		for _ in range(t):
			N = int(input().strip())
			adj_list = [[] for _ in range(N + 1)]
			adj_list[0] = None
			for _ in range(N - 1):
				(a, b) = get_int()
				adj_list[a].append(b)
				adj_list[b].append(a)
			imp_edges = []
			heapq.heapify(imp_edges)
			visited = [False] * (N + 1)
			visited[1] = True
			dfs(adj_list, imp_edges, visited, N)
			int(input())
			fctrs = get_int()
			fctrs.sort()
			ans = 0
			while len(fctrs) > len(imp_edges):
				lst_fctr = fctrs.pop() * fctrs.pop() % mod
				fctrs.append(lst_fctr)
			while len(imp_edges) > 0:
				ans = (ans % mod + abs(imp_edges[0][0]) * (1 if len(fctrs) == 0 else fctrs.pop()) % mod) % mod
				heapq.heappop(imp_edges)
			print(ans)
threading.Thread(target=solve).start()


import sys
from collections import defaultdict, deque

def bfs(node):
	q = deque([node])
	vis[node] = 1
	res = []
	while q:
		x = q.popleft()
		vis[x] = 1
		res.append(x)
		for j in edge[x]:
			if vis[j] == 0:
				child[x].append(j)
				q.append(j)
	res.reverse()
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	z = 10 ** 9 + 7
	edge = defaultdict(list)
	child = defaultdict(list)
	for j in range(n - 1):
		(u, v) = list(map(int, input().split()))
		edge[u].append(v)
		edge[v].append(u)
	m = int(input())
	arr = list(map(int, input().split()))
	vis = [0] * (n + 1)
	subTreeSize = [1] * (n + 1)
	res = bfs(1)
	for i in res:
		for j in child[i]:
			subTreeSize[i] += subTreeSize[j]
	num = []
	for i in res:
		for j in child[i]:
			num.append(subTreeSize[j] * (n - subTreeSize[j]))
	num.sort(reverse=True)
	arr.sort(reverse=True)
	a = n - 1 - len(arr)
	if a > 0:
		for i in range(a):
			arr.append(1)
	else:
		for i in range(1, abs(a) + 1):
			arr[0] *= arr[i]
			arr[0] %= z
	ans = 0
	if a > 0:
		for i in range(n - 1):
			ans += arr[i] * num[i]
			ans %= z
	else:
		for i in range(n - 1):
			if i == 0:
				ans += arr[i] * num[i]
				ans %= z
			else:
				ans += arr[i + abs(a)] * num[i]
				ans %= z
	print(ans)


DISTRIBUTION_INDEX_MOD = 10 ** 9 + 7

def compute_max_distribution_index(graph, factors_seq):
	edges_loading = _compute_edges_loading(graph)
	loadings = sorted(edges_loading.values(), reverse=True)
	edges_n = len(loadings)
	weights = [1] * edges_n
	factors_seq = sorted(factors_seq)
	(first_factors, factors_remain) = (factors_seq[:edges_n], factors_seq[edges_n:])
	i_edge = 0
	while first_factors:
		weights[i_edge] *= first_factors.pop()
		weights[i_edge] %= DISTRIBUTION_INDEX_MOD
		i_edge += 1
	for factor in factors_remain:
		weights[0] *= factor
		weights[0] %= DISTRIBUTION_INDEX_MOD
	result = 0
	for (loading, weight) in zip(loadings, weights):
		loading %= DISTRIBUTION_INDEX_MOD
		result += loading * weight % DISTRIBUTION_INDEX_MOD
		result %= DISTRIBUTION_INDEX_MOD
	return result

def _compute_edges_loading(graph):
	vertices_n = len(graph)
	edges_loading = dict()
	leaves = [vertex for vertex in range(len(graph)) if len(graph[vertex]) == 1]
	vertices_accumulated = [None] * len(graph)
	for leave in leaves:
		vertices_accumulated[leave] = 1
		neighbors = graph[leave]
		assert len(neighbors) == 1
		next_vertex = tuple(neighbors)[0]
		edges_loading[frozenset((leave, next_vertex))] = _compute_edge_loading(vertices_accumulated[leave], vertices_n)
	active = set().union(*(graph[leave] for leave in leaves))
	passed = set(leaves)
	active -= passed
	while len(passed) < len(graph):
		old_active = active
		active = set()
		for vertex in old_active:
			neighbors = graph[vertex]
			neighbors_not_passed = neighbors - passed
			if len(neighbors_not_passed) > 1:
				active.add(vertex)
				continue
			vertices_accumulated[vertex] = sum((vertices_accumulated[neighbor] for neighbor in neighbors if neighbor in passed)) + 1
			for neighbor in neighbors_not_passed:
				edges_loading[frozenset((vertex, neighbor))] = _compute_edge_loading(vertices_accumulated[vertex], vertices_n)
			passed.add(vertex)
			active.update(neighbors_not_passed)
		active = active - passed
	return edges_loading

def _compute_edge_loading(accumulated_n, vertices_n):
	return accumulated_n * (vertices_n - accumulated_n)

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		graph = tuple((set() for i in range(n)))
		for i_edge in range(n - 1):
			(v1, v2) = map(int, input().split())
			(v1, v2) = (v1 - 1, v2 - 1)
			graph[v1].add(v2)
			graph[v2].add(v1)
		m = int(input())
		factors_seq = tuple(map(int, input().split()))
		result = compute_max_distribution_index(graph, factors_seq)
		print(result)
main()


from sys import stdin
input = lambda : stdin.readline().strip()
lin = lambda : list(map(int, input().split()))
iin = lambda : int(input())
main = lambda : map(int, input().split())
from math import ceil, sqrt, factorial, log
from collections import deque
from bisect import bisect_left

def gcd(a, b):
	(a, b) = (max(a, b), min(a, b))
	while a % b != 0:
		(a, b) = (b, a % b)
	return b
mod = 998244353
mod = 1000000007

def dfs(tree, n):
	child = {i: 1 for i in range(n)}
	parent = {i: -1 for i in range(n)}
	vis = [0] * n
	s = deque([0])
	q = []
	while s:
		x = s.popleft()
		q.append(x)
		vis[x] = 1
		for i in tree[x]:
			if vis[i] == 0:
				s.append(i)
				parent[i] = x
	for i in range(n - 1, 0, -1):
		child[parent[q[i]]] += child[q[i]]
	l = []
	for i in range(1, n):
		l.append(child[i] * (n - child[i]))
	l.sort()
	return l

def solve(we):
	n = iin()
	tree = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = main()
		u -= 1
		v -= 1
		tree[u].append(v)
		tree[v].append(u)
	z = dfs(tree, n)
	m = iin()
	l = lin()
	l.sort()
	if m < n - 1:
		l = [1 for i in range(n - m - 1)] + l
	else:
		t = 1
		for i in range(n - 2, m):
			t *= l[i]
			t = t % mod
		l = l[:n - 2] + [t]
	ans = 0
	for i in range(n - 1):
		ans = (ans + z[i] * l[i] % mod) % mod
	print(ans)
qwe = 1
qwe = iin()
for _ in range(qwe):
	solve(_ + 1)


from sys import stdin, stdout

def input():
	return stdin.readline().strip()
tests = int(input())
for t in range(tests):
	n = int(input())
	node_dict = {}
	for _ in range(n - 1):
		(u, v) = list(map(int, input().split()))
		if u in node_dict:
			node_dict[u][0] += 1
			node_dict[u][1].add(v)
		else:
			node_dict[u] = [1, set([v])]
		if v in node_dict:
			node_dict[v][0] += 1
			node_dict[v][1].add(u)
		else:
			node_dict[v] = [1, set([u])]
	num_primes = int(input())
	prime_ls = sorted(list(map(int, input().split())))
	edge_weight = []
	visit_node = [True for _ in range(0, n + 1)]
	other_node = list(node_dict[1][1])[0]
	stack = [[1, 0], [other_node, 0]]
	visit_node[1] = True
	node_dict[1][0] -= 1
	node_dict[1][1].remove(other_node)
	node_dict[other_node][0] -= 1
	node_dict[other_node][1].remove(1)
	while stack:
		(curr, excess) = stack[-1]
		visit_node[curr] = False
		if node_dict[curr][0] == 0:
			stack.pop()
			if stack:
				edge_weight.append((n - excess - 1) * (excess + 1))
				stack[-1][1] += 1 + excess
		else:
			new_node = node_dict[curr][1].pop()
			node_dict[curr][0] -= 1
			while node_dict[curr][0] != 0 and (not visit_node[new_node]):
				new_node = node_dict[curr][1].pop()
				node_dict[curr][0] -= 1
			if visit_node[new_node]:
				stack.append([new_node, 0])
	edge_weight = sorted(edge_weight)
	res = 0
	if num_primes > n - 1:
		prod = 1
		for idx in range(num_primes - 1, n - 3, -1):
			prod *= prime_ls[idx]
			prod = prod % 1000000007
		prime_ls[n - 2] = prod
		for idx in range(n - 1):
			res += edge_weight[idx] * prime_ls[idx] % 1000000007
			res = res % 1000000007
	else:
		start_idx = n - 2
		for idx in range(num_primes - 1, -1, -1):
			res += edge_weight[start_idx] * prime_ls[idx]
			res = res % 1000000007
			start_idx -= 1
		for idx in range(start_idx + 1):
			res += edge_weight[idx]
			res = res % 1000000007
	print(res % 1000000007)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def main():
	for ik in range(int(input())):
		n = int(input())
		graph = defaultdict(list)
		for i in range(n - 1):
			(a, b) = map(int, input().split())
			graph[a - 1].append(b - 1)
			graph[b - 1].append(a - 1)
		k = int(input())
		l = list(map(int, input().split()))
		l.sort(reverse=True)
		fact = [1 for i in range(n - 1)]
		if len(l) <= n - 1:
			fact[0] = l[0]
			st = 0
		else:
			n1 = n - 1
			for i in range(len(l) - n1 + 1):
				fact[0] *= l[i]
				fact[0] %= mod
				st = i
		st += 1
		t = 1
		for i in range(st, len(l)):
			fact[t] = l[i]
			t += 1
		child = [0] * n
		visited = [False] * n

		def DFS(v, visited):
			visited[v] = True
			c = 1
			for i in graph[v]:
				if visited[i] == False:
					c += DFS(i, visited)
			child[v] = c
			return c
		DFS(0, visited)
		for i in range(n):
			r = n - child[i]
			child[i] = n * (n - 1) - child[i] * (child[i] - 1) - r * (r - 1)
			child[i] //= 2
		child = child[1:]
		child.sort(reverse=True)
		ans = 0
		for i in range(n - 1):
			ans += child[i] * fact[i] % mod
			ans %= mod
		print(ans)
t = threading.Thread(target=main)
t.start()
t.join()


import sys
input = sys.stdin.buffer.readline
mod = 10 ** 9 + 7

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		g = [[] for _ in range(n)]
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			(u, v) = (u - 1, v - 1)
			g[u].append(v)
			g[v].append(u)
		m = int(input())
		P = list(map(int, input().split()))
		P.sort()
		s = []
		visit = [-1] * n
		s.append(0)
		order = []
		par = [-1] * n
		while s:
			v = s.pop()
			order.append(v)
			for u in g[v]:
				if u == par[v]:
					continue
				par[u] = v
				s.append(u)
		ans = 0
		c = [1] * n
		order.reverse()
		U = []
		for v in order:
			if par[v] != -1:
				cnt = (n - c[v]) * c[v]
				U.append(cnt)
				c[par[v]] += c[v]
		if len(U) >= len(P):
			U.sort(reverse=True)
			ans = 0
			for u in U:
				if P:
					p = P.pop()
				else:
					p = 1
				ans += u * p
				ans %= mod
		else:
			U.sort()
			P.sort()
			Q = P[0:len(U)]
			R = P[len(U):]
			for r in R:
				Q[-1] *= r
				Q[-1] %= mod
			for (u, q) in zip(U, Q):
				ans += u * q
				ans %= mod
		print(ans)
main()


import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192

def str(x=b''):
	return x if type(x) is bytes else _str(x).encode()

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())

def tree_bfs(tree, flat=True, start=0) -> list:
	stack = [start]
	result = []
	while stack:
		new_stack = []
		if flat:
			result.extend(stack)
		else:
			result.append(stack)
		for node in stack:
			new_stack.extend(tree[node])
		stack = new_stack
	return result

def tree_postorder(tree, flat=True, root=0):
	return tree_bfs(tree, flat, root)[::-1]

def get_parent_list(tree):
	result = [0] * len(tree)
	for (parent, children) in enumerate(tree):
		for child in children:
			result[child] = parent
	return result

def to_tree(graph, root=0):
	stack = [[root]]
	while stack:
		if not stack[-1]:
			del stack[-1]
			continue
		parent = stack[-1].pop()
		for child in graph[parent]:
			graph[child].discard(parent)
		stack.append(list(graph[parent]))

def edge_descendant(tree, edge_time_count=False):
	vertices = len(tree)
	results = [{} for _ in range(vertices)]
	parent_list = get_parent_list(tree)
	for child in tree_postorder(tree):
		parent = parent_list[child]
		if parent != child:
			results[parent][child] = sum(results[child].values()) + 1
	if edge_time_count:
		for parent in results:
			for child in parent:
				num = parent[child]
				parent[child] = num * (vertices - num)
	return results
from itertools import chain
from functools import reduce
MOD = 10 ** 9 + 7

def solve():
	n = itg()
	tree = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = mpint()
		tree[u - 1].add(v - 1)
		tree[v - 1].add(u - 1)
	to_tree(tree)
	m = itg()
	factors = sorted(mpint())
	count = sorted(chain(*[d.values() for d in edge_descendant(tree, True)]))
	n -= 1
	if n >= m:
		factors = [1] * (n - m) + factors
	else:
		while len(factors) != n:
			factors[-1] = factors[-2] * factors.pop() % MOD
	return reduce(lambda a, b: (a + b) % MOD, (time * value % MOD for (time, value) in zip(count, factors)), 0)

def main():
	for _ in range(itg()):
		print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1401/problem/D'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
elif DEBUG == 2:
	main()
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import deque, defaultdict
import heapq
for j in range(int(input())):
	n = int(input())
	tree = [set([]) for s in range(n)]
	mod = 10 ** 9 + 7
	for s in range(n - 1):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		tree[u].add(v)
		tree[v].add(u)
	m = int(input())
	vals = list(map(int, input().split()))
	depth = defaultdict(list)
	dd = {}
	q = deque([])
	vis = set([])
	cv = 0
	pr = 1
	for s in range(n):
		if len(tree[s]) >= 1:
			q.append(s)
			vis.add(s)
			break
	while len(q) > 0:
		vv = q.popleft()
		for s in tree[vv]:
			if not s in vis:
				q.append(s)
				vis.add(s)
		depth[cv].append(vv)
		dd[vv] = cv
		pr -= 1
		if pr == 0:
			cv += 1
			pr = len(q)
	cv = max(depth.keys())
	dist = defaultdict(list)
	while cv > 0:
		for s in depth[cv]:
			for b in tree[s]:
				if cv > dd[b]:
					dist[b].append(sum(dist[s]) + 1)
		cv -= 1
	visits = []
	heapq.heapify(visits)
	vals.sort()
	ans = 0
	for s in dist.keys():
		while len(dist[s]) > 0:
			v1 = dist[s].pop()
			if v1 != 0:
				heapq.heappush(visits, -v1 * (n - v1))
	if len(vals) > len(visits):
		prod = 1
		while len(vals) >= len(visits):
			prod *= vals.pop()
			prod = prod % mod
		ans += -heapq.heappop(visits) * prod % mod
	while len(visits) > 0:
		v2 = -heapq.heappop(visits)
		if len(vals) > 0:
			ans += v2 * vals.pop()
		else:
			ans += v2
		ans = ans % mod
	print(ans)


import io
import os
from collections import Counter, defaultdict, deque
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
MOD = 10 ** 9 + 7

def solve(N, edges, M, P):
	P.sort()
	if len(P) > N - 1:
		edgeVals = P[:N - 1]
		last = 1
		for i in range(N - 1, len(P)):
			last = last * P[i] % MOD
		edgeVals[-1] = edgeVals[-1] * last % MOD
	else:
		edgeVals = [1] * (N - 1 - len(P)) + P
	assert len(edgeVals) == N - 1
	graph = [[] for i in range(N)]
	for (u, v) in edges:
		graph[u].append(v)
		graph[v].append(u)
	size = [0 for i in range(N)]

	@bootstrap
	def dfs(node, p):
		total = 1
		for child in graph[node]:
			if child != p:
				yield dfs(child, node)
				total += size[child]
		size[node] = total
		yield
	dfs(0, -1)
	edges2 = []
	for (i, (u, v)) in enumerate(edges):
		left = min(size[u], size[v])
		right = N - left
		edges2.append(left * right)
	edges2.sort()
	ans = 0
	for (count, vals) in zip(edges2, edgeVals):
		ans += count * vals
		ans %= MOD
	return ans % MOD
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)]
	(M,) = [int(x) for x in input().split()]
	P = [int(x) for x in input().split()]
	ans = solve(N, edges, M, P)
	print(ans)


import sys

def input():
	return sys.stdin.readline()[:-1]
mod = 10 ** 9 + 7

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		e_list = [[] for i in range(n)]
		for j in range(n - 1):
			(a, b) = list(map(int, input().split()))
			(a, b) = (a - 1, b - 1)
			e_list[a].append(b)
			e_list[b].append(a)
		m = int(input())
		p = list(map(int, input().split()))
		from collections import deque
		vi = 0
		INF = float('inf')
		Q = deque([vi])
		checked_list = [False] * n
		checked_list[vi] = True
		parent_list = [-1] * n
		min_path_list = [INF] * n
		min_path_list[vi] = 0
		while len(Q) > 0:
			v = Q.pop()
			for v1 in e_list[v]:
				if not checked_list[v1]:
					checked_list[v1] = True
					Q.appendleft(v1)
					parent_list[v1] = v
					min_path_list[v1] = min_path_list[v] + 1
		memo = [-1] * n
		min_path = [(i, min_path_list[i]) for i in range(n)]
		min_path.sort(key=lambda x: x[1], reverse=True)
		for (v, d) in min_path:
			if v == 0:
				continue
			count = 0
			for v1 in e_list[v]:
				if v1 != parent_list[v]:
					count += memo[v1] + 1
			memo[v] = count
		memo = [(memo[i] + 1) * (n - memo[i] - 1) for i in range(1, n)]
		memo.sort(reverse=True)
		p.sort(reverse=True)
		ans = 0
		if m <= n - 1:
			for i in range(m):
				ans += p[i] * memo[i]
				ans %= mod
			for i in range(m, n - 1):
				ans += memo[i]
				ans %= mod
		else:
			a = 1
			for i in range(m - n + 2):
				a *= p[i]
				a %= mod
			ans = a * memo[0]
			ans %= mod
			for i in range(1, n - 1):
				ans += p[i + m - n + 1] * memo[i]
				ans %= mod
		print(ans)
main()


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
import sys
sys.setrecursionlimit(10 ** 5 + 10)
from types import GeneratorType

def bootstrap(func, stack=[]):

	def wrapped_function(*args, **kwargs):
		if stack:
			return func(*args, **kwargs)
		else:
			call = func(*args, **kwargs)
			while True:
				if type(call) is GeneratorType:
					stack.append(call)
					call = next(call)
				else:
					stack.pop()
					if not stack:
						break
					call = stack[-1].send(call)
			return call
	return wrapped_function
mod = int(1000000000.0 + 7)
for _ in range(int(input())):
	n = int(input())
	gr = defaultdict(list)
	for i in range(n - 1):
		(x, y) = mapi()
		gr[x].append(y)
		gr[y].append(x)
	m = int(input())
	p = list(mapi())
	while len(p) < n - 1:
		p.append(1)
	p.sort()
	for i in range(n - 1, len(p), 1):
		p[n - 2] = p[n - 2] * p[i] % mod
	p = p[:n - 1]
	p = p[::-1]
	sz = [1] * (n + 1)

	@bootstrap
	def dfs(s, par):
		for i in gr[s]:
			if i == par:
				continue
			yield dfs(i, s)
			sz[s] += sz[i]
		yield 0
	dfs(1, -1)
	count = []
	for i in range(1, n + 1):
		count.append(sz[i] * (n - sz[i]))
	count.sort(reverse=True)
	res = 0
	for i in range(n - 1):
		res += p[i] * count[i] % mod
		res %= mod
	print(res)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
MOD = 10 ** 9 + 7
q = int(input())
for _ in range(q):
	n = int(input())
	adj_lis = [[] for i in range(n)]
	adj_cnt = [0] * n
	adj_cnt[0] = 1
	par = [-1] * n
	des_cnt = [1] * n
	leaf_q = []
	edgeNum = []
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		adj_lis[u - 1].append(v - 1)
		adj_lis[v - 1].append(u - 1)
		adj_cnt[u - 1] += 1
		adj_cnt[v - 1] += 1
	tree_q = [(0, -1)]
	while tree_q:
		(v, par_v) = tree_q.pop()
		par[v] = par_v
		for x in adj_lis[v]:
			if x != par_v:
				tree_q.append((x, v))
		if adj_cnt[v] == 1:
			leaf_q.append(v)
	while leaf_q:
		x = leaf_q.pop()
		if x == 0:
			continue
		edgeNum.append(des_cnt[x] * (n - des_cnt[x]))
		des_cnt[par[x]] += des_cnt[x]
		adj_cnt[par[x]] -= 1
		if adj_cnt[par[x]] == 1:
			leaf_q.append(par[x])
	edgeNum.sort()
	m = int(input())
	edgeWeight = []
	primeList = list(map(int, input().split()))
	primeList.sort()
	if n - 1 < m:
		for i in range(n - 1):
			edgeWeight.append(primeList[i])
		for i in range(n - 1, m):
			edgeWeight[n - 2] *= primeList[i]
			edgeWeight[n - 2] %= MOD
	else:
		for i in range(n - 1 - m):
			edgeWeight.append(1)
		for i in range(m):
			edgeWeight.append(primeList[i])
	ans = 0
	for i in range(n - 1):
		ans += edgeNum[i] * edgeWeight[i]
		ans %= MOD
	print(ans)


import sys
import threading
from sys import stdin, stdout
sys.setrecursionlimit(10 ** 9)
threading.stack_size(16 * 2048 * 2048)

def maximum_distributed_tree(n, uv_dic, p_a, edg):
	MOD = 10 ** 9 + 7
	dfs(n, uv_dic, 1, -1, edg)
	edg.sort(reverse=True)
	p_a.sort(reverse=True)
	res = 0
	if len(p_a) - n + 1 > 0:
		for i in range(1, len(p_a) - n + 2):
			p_a[i] *= p_a[i - 1]
			p_a[i] %= MOD
		del p_a[:len(p_a) - n + 1]
	for i in range(len(p_a)):
		res += edg[i] * p_a[i]
		res %= MOD
	for i in range(len(p_a), n - 1):
		res += edg[i]
		res %= MOD
	return res

def dfs(n, uv_dic, node, parent, edg):
	cnt = 1
	nxt_a = uv_dic[node]
	for nxt in nxt_a:
		if nxt[1] != parent:
			nxtCnt = dfs(n, uv_dic, nxt[1], node, edg)
			edg[nxt[0]] = nxtCnt * (n - nxtCnt)
			cnt += nxtCnt
	return cnt

def solve():
	try:
		t = int(stdin.readline())
		for _ in range(t):
			n = int(stdin.readline())
			uv_dic = {}
			edg = [0 for _ in range(n - 1)]
			for i in range(n - 1):
				(u, v) = map(int, stdin.readline().split())
				if u not in uv_dic:
					uv_dic[u] = []
				if v not in uv_dic:
					uv_dic[v] = []
				uv_dic[u].append([i, v])
				uv_dic[v].append([i, u])
			m = int(stdin.readline())
			p_a = list(map(int, stdin.readline().split()))
			ans = maximum_distributed_tree(n, uv_dic, p_a, edg)
			stdout.write(str(ans) + '\n')
	except Exception as e:
		print(''.join(str(e).split()))
threading.Thread(target=solve).start()


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	a = [[] for i in range(n + 1)]
	dg = [0] * (n + 1)
	for i in range(n - 1):
		(x, y) = R()
		dg[x] += 1
		dg[y] += 1
		a[x] += (y,)
		a[y] += (x,)
	mn = dg.index(1)
	stk = [mn]
	val = [mn]
	v = [0] * (n + 1)
	s = [1] * (n + 1)
	vst = [1] * (n + 1)
	vst[mn] = 0
	while stk:
		p = stk.pop()
		for el in a[p]:
			if vst[el]:
				stk += (el,)
				val += (el,)
				v[el] = p
				vst[el] = 0
	ans = []
	for i in val[1:][::-1]:
		s[v[i]] += s[i]
		ans += (s[i] * (n - s[i]),)
	m = I()
	p = [1] * max(0, n - 1 - m) + sorted(R())
	if m > n - 1:
		for i in range(m - (n - 1)):
			p[-1] = p[-2] * p.pop() % N
	ans.sort()
	x = 0
	for i in range(n - 1):
		x = (x + p[i] * ans[i] % N) % N
	print(x)


from collections import defaultdict
import sys
from types import GeneratorType
MOD = 10 ** 9 + 7

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def rl():
	return [int(w) for w in sys.stdin.readline().split()]

@bootstrap
def number_of_nodes(s, e):
	counts[s] = 1
	for u in edges[s]:
		if u == e:
			continue
		yield number_of_nodes(u, s)
		counts[s] += counts[u]
	yield
for _ in range(rl()[0]):
	(n,) = rl()
	edges = defaultdict(set)
	for _ in range(n - 1):
		(u, v) = rl()
		edges[u - 1].add(v - 1)
		edges[v - 1].add(u - 1)
	(m,) = rl()
	p = rl()
	p.sort(reverse=True)
	counts = [0] * n
	number_of_nodes(0, -1)
	edge_frequency = []
	for i in range(1, n):
		edge_frequency.append(counts[i] * (n - counts[i]))
	edge_frequency.sort(reverse=True)
	while m < n - 1:
		p.append(1)
		m += 1
	if m > n - 1:
		d = m - (n - 1) + 1
		a = 1
		for i in range(d):
			a *= p[i]
			a %= MOD
		p = [a] + p[d:]
	f = 0
	for i in range(n - 1):
		f = (f + edge_frequency[i] * p[i]) % MOD
	print(f)


import sys
input = sys.stdin.buffer.readline
T = int(input())
MOD = 10 ** 9 + 7
for testcase in range(T):
	n = int(input())
	edge = [[] for i in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		edge[u - 1].append(v - 1)
		edge[v - 1].append(u - 1)
	m = int(input())
	p = list(map(int, input().split()))
	par = [-2] * n
	par[0] = -1
	tank = [0]
	order = []
	while tank:
		now = tank.pop()
		order.append(now)
		for nxt in edge[now]:
			if par[nxt] == -2:
				par[nxt] = now
				tank.append(nxt)
	size = [1] * n
	for e in order[::-1]:
		if e == 0:
			continue
		size[par[e]] += size[e]
	for i in range(n):
		size[i] *= n - size[i]
	if m <= n - 1:
		p.sort()
		size.sort()
		res = 0
		for i in range(1, n):
			if i < n - m:
				res = (res + size[i]) % MOD
			else:
				res = (res + size[i] * p[i - (n - m)]) % MOD
		print(res % MOD)
	else:
		p.sort()
		size.sort()
		res = 0
		mul = 1
		for i in range(m):
			if i < n - 2:
				res = (res + size[i + 1] * p[i]) % MOD
			else:
				mul = mul * p[i] % MOD
		res = (res + mul * size[-1]) % MOD
		print(res % MOD)


import math
from sys import stdin
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')

def mul(a, b):
	return a % mod * (b % mod) % mod
(t,) = gil()
for _ in range(t):
	(n,) = gil()
	adj = [[] for _ in range(n + 1)]
	for _ in range(n - 1):
		(x, y) = gil()
		adj[x].append(y)
		adj[y].append(x)
	(m,) = gil()
	fac = gil()
	fac.sort()
	while len(fac) >= n:
		v = fac.pop()
		fac[-1] = mul(v, fac[-1])
	(dfs, vis, cnt, fin, edges) = ([1], [0] * (n + 1), [1] * (n + 1), [0] * (n + 1), [])
	while dfs:
		x = dfs[-1]
		if vis[x]:
			dfs.pop()
			for y in adj[x]:
				if fin[y]:
					cnt[x] += cnt[y]
					edges.append(cnt[y] * (n - cnt[y]))
			fin[x] = 1
		else:
			vis[x] = 1
			for y in adj[x]:
				if vis[y] == 0:
					dfs.append(y)
	edges.sort()
	ans = 0
	while edges and fac:
		ans = (mul(fac.pop(), edges.pop()) + ans) % mod
	while edges:
		ans = (ans + edges.pop()) % mod
	print(ans % mod)


import math, sys
from collections import defaultdict, deque
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

def I():
	return int(sys.stdin.readline())

def In():
	return map(int, sys.stdin.readline().split())

def Sn():
	return sys.stdin.readline().strip()

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(node, d):
	if visit[node]:
		return
	visit[node] = True
	su = 0
	for x in d[node]:
		if not visit[x]:
			su += (yield dfs(x, d))
	dp[node] = su + 1
	yield (su + 1)

def main():
	try:
		global visit, dp
		n = I()
		d = defaultdict(list)
		for x in range(n - 1):
			(a, b) = In()
			d[a].append(b)
			d[b].append(a)
		m = I()
		primes = list(In())
		primes.sort()
		dp = [0] * (n + 1)
		visit = [False] * (n + 1)
		dfs(1, d)
		time = []
		for i in range(1, n + 1):
			z = (n - dp[i]) * dp[i]
			if z:
				time.append(z)
		time.sort()
		ans = 0
		if m > len(time):
			j = 0
			for i in range(len(time) - 1):
				ans = ans % P + time[i] % P * primes[j] % P
				ans %= P
				j += 1
			an = 1
			for i in range(j, m):
				an *= primes[i]
				an %= P
			ans = ans % P + time[-1] % P * an % P
			print(ans % P)
		else:
			te = []
			for i in range(len(time) - m):
				te.append(1)
			te += primes
			for i in range(len(time)):
				ans += time[i] % P * te[i] % P
				ans %= P
			print(ans % P)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


from sys import stdin, stdout
from collections import defaultdict
MOD = 10 ** 9 + 7

def KK(G, N):
	st = [0]
	P = [-1] * N
	P[0] = 0
	for i in st:
		for j in G[i]:
			if P[j] != -1:
				continue
			P[j] = i
			st.append(j)
	CH = [1] * N
	while st:
		a = st.pop()
		CH[P[a]] += CH[a]
	return CH

def find(g, PR, N, m):
	ch = KK(g, N)
	arr = []
	for i in range(1, N):
		arr.append(ch[i] * (N - ch[i]))
	PR.sort()
	arr.sort()
	while len(PR) > len(arr):
		PR.append(PR.pop() * PR.pop() % MOD)
	r = 0
	while arr:
		a = arr.pop()
		b = PR.pop() if PR else 1
		r = (r + a * b) % MOD
	return r

def main():
	for _ in range(int(stdin.readline())):
		N = int(stdin.readline())
		g = [[] for _ in range(N)]
		for _ in range(N - 1):
			(a, b) = list(map(int, stdin.readline().split()))
			g[a - 1].append(b - 1)
			g[b - 1].append(a - 1)
		m = int(stdin.readline())
		arr = list(map(int, stdin.readline().split()))
		print(find(g, arr, N, m))
main()


from collections import defaultdict
import sys
input = sys.stdin.readline
t = int(input())
for ii in range(t):
	n = int(input())
	graph = defaultdict(list)
	edge = defaultdict(int)
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		graph[u].append(v)
		graph[v].append(u)
		edge[min(u, v), max(u, v)] = 0
	m = int(input())
	p = [int(i) for i in input().split() if i != '\n']
	p.sort(reverse=True)
	OBSERVE = 0
	CHECK = 1
	stack = [(OBSERVE, 1, 0)]
	count = [0] * (n + 1)
	while stack:
		(state, vertex, parent) = stack.pop()
		if state == OBSERVE:
			stack.append((CHECK, vertex, parent))
			for child in graph[vertex]:
				if child != parent:
					stack.append((OBSERVE, child, vertex))
		else:
			if len(graph[vertex]) == 1:
				count[vertex] = 1
			for child in graph[vertex]:
				if child != parent:
					edge[min(child, vertex), max(child, vertex)] = count[child] * (n - count[child])
					count[vertex] += count[child]
			if len(graph[vertex]) != 1:
				count[vertex] += 1
	rep = []
	(ans, prod) = (0, 1)
	for i in edge:
		rep.append(edge[i])
	rep.sort(reverse=True)
	diff = 0
	if m > n - 1:
		diff = m - n + 1
		for i in range(diff + 1):
			prod *= p[i]
			prod %= 10 ** 9 + 7
	else:
		prod = p[0]
	ans += prod * rep[0] % (10 ** 9 + 7)
	for i in range(1, len(rep)):
		if i >= len(p):
			ans += rep[i]
			ans %= 10 ** 9 + 7
		else:
			ans += p[i + diff] * rep[i]
			ans %= 10 ** 9 + 7
	sys.stdout.write(str(ans) + '\n')


import sys, threading

def main():

	def dfs(vertex, sizes, graph, parent):
		for u in graph[vertex]:
			if u != parent:
				sizes[vertex] += dfs(u, sizes, graph, vertex)
		return sizes[vertex]
	t = int(input())
	for i in range(t):
		n = int(input())
		e = []
		for j in range(n - 1):
			(u, v) = map(int, input().split())
			u -= 1
			v -= 1
			e.append((u, v))
		g = [[] for j in range(n)]
		for f in e:
			g[f[0]].append(f[1])
			g[f[1]].append(f[0])
		m = int(input())
		pr = list(map(int, input().split()))
		if m > n - 1:
			pr.sort()
			while len(pr) > n - 1:
				pr[-2] *= pr[-1]
				pr.pop()
				pr[-1] %= 1000000007
		else:
			while len(pr) < n - 1:
				pr.append(1)
			pr.sort()
		l = [1 for j in range(n)]
		dfs(0, l, g, -1)
		l.pop(0)
		for j in range(n - 1):
			l[j] = l[j] * (n - l[j])
		l.sort()
		s = 0
		for j in range(n - 1):
			s += pr[j] * l[j]
			s %= 1000000007
		print(s)
sys.setrecursionlimit(5 * 10 ** 5)
threading.stack_size(1 << 27)
thread = threading.Thread(target=main)
thread.start()
thread.join()


from sys import stdin
input = stdin.readline
t = int(input())
mod = 10 ** 9 + 7
for _ in range(t):
	n = int(input())
	g = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		g[u - 1].append(v - 1)
		g[v - 1].append(u - 1)
	m = int(input())
	p = list(map(int, input().split()))
	p.sort()
	z = []
	if m < n - 1:
		z = [1] * (n - 1 - m) + p
	else:
		z = p
		tmp = 1
		for i in range(m - n + 1):
			tmp = tmp * p[-i - 1] % mod
		z[n - 2] = z[n - 2] * tmp % mod
	top = []
	q = [0]
	use = [False] * n
	use[0] = 1
	par = [-1] * n
	while q:
		ver = q.pop()
		top.append(ver)
		for to in g[ver]:
			if not use[to]:
				use[to] = True
				par[to] = ver
				q.append(to)
	w = []
	l = [1] * n
	for ver in top[1:][::-1]:
		w.append(l[ver] * (n - l[ver]))
		l[par[ver]] += l[ver]
	w.sort()
	ans = 0
	for i in range(n - 1):
		ans = (ans + w[i] * z[i]) % mod
	print(ans)


import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
res = []
q = int(input())
for _ in range(q):
	n = int(input())
	adj_lis = [[] for i in range(n)]
	adj_cnt = [0] * n
	adj_cnt[0] = 1
	par = [-1] * n
	des_cnt = [1] * n
	leaf_q = []
	edgeNum = []
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		adj_lis[u - 1].append(v - 1)
		adj_lis[v - 1].append(u - 1)
		adj_cnt[u - 1] += 1
		adj_cnt[v - 1] += 1
	tree_q = [(0, -1)]
	while tree_q:
		(v, par_v) = tree_q.pop()
		par[v] = par_v
		for x in adj_lis[v]:
			if x != par_v:
				tree_q.append((x, v))
		if adj_cnt[v] == 1:
			leaf_q.append(v)
	while leaf_q:
		x = leaf_q.pop()
		if x == 0:
			continue
		edgeNum.append(des_cnt[x] * (n - des_cnt[x]))
		des_cnt[par[x]] += des_cnt[x]
		adj_cnt[par[x]] -= 1
		if adj_cnt[par[x]] == 1:
			leaf_q.append(par[x])
	edgeNum.sort()
	m = int(input())
	edgeWeight = []
	primeList = list(map(int, input().split()))
	primeList.sort()
	if n - 1 < m:
		for i in range(n - 1):
			edgeWeight.append(primeList[i])
		for i in range(n - 1, m):
			edgeWeight[n - 2] *= primeList[i]
			edgeWeight[n - 2] %= MOD
	else:
		for i in range(n - 1 - m):
			edgeWeight.append(1)
		for i in range(m):
			edgeWeight.append(primeList[i])
	ans = 0
	for i in range(n - 1):
		ans += edgeNum[i] * edgeWeight[i]
		ans %= MOD
	res.append(ans)
print('\n'.join(map(str, res)))


import sys, math
import io, os

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
from decimal import Decimal
INF = float('inf')
mod = int(1000000000.0) + 7

def dfs(graph, start=0):
	n = len(graph)
	dp = [0] * n
	(visited, finished) = ([False] * n, [False] * n)
	stack = [start]
	while stack:
		start = stack[-1]
		if not visited[start]:
			visited[start] = True
			for child in graph[start]:
				if not visited[child]:
					stack.append(child)
		else:
			stack.pop()
			dp[start] += 1
			for child in graph[start]:
				if finished[child]:
					dp[start] += dp[child]
			finished[start] = True
	return dp
for t in range(int(data())):
	n = int(data())
	graph = [[] for i in range(n)]
	for i in range(n - 1):
		(u, v) = mdata()
		graph[u - 1].append(v - 1)
		graph[v - 1].append(u - 1)
	dp = dfs(graph)
	l = []
	s = [0]
	vis = [0] * n
	while s:
		a = s.pop()
		vis[a] = 1
		for i in graph[a]:
			if vis[i] == 0:
				l.append((n - dp[i]) * dp[i])
				s.append(i)
	l.sort()
	m = int(data())
	p = sorted(mdata())
	ans = 0
	if len(l) <= m:
		for i in range(n - 2):
			ans = (ans + l[i] * p[i]) % mod
		k = l[-1]
		for i in range(n - 2, m):
			k = k * p[i] % mod
		ans = (ans + k) % mod
	else:
		for i in range(m):
			ans = (ans + l[n - i - 2] * p[m - i - 1]) % mod
		ans = (ans + sum(l[:n - 1 - m])) % mod
	out(ans)


from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(node, edge, parentNode):
	subtreeNodeCnt = 1
	for (v, edge2) in adj[node]:
		if v == parentNode:
			continue
		subtreeNodeCnt += (yield dfs(v, edge2, node))
	evc[edge] += subtreeNodeCnt * (n - subtreeNodeCnt)
	yield subtreeNodeCnt
import sys
input = sys.stdin.buffer.readline
M = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	n = int(input())
	adj = [[] for __ in range(n + 1)]
	for i in range(n - 1):
		(u, v) = [int(x) for x in input().split()]
		adj[u].append([v, i])
		adj[v].append([u, i])
	m = int(input())
	p = [int(x) for x in input().split()]
	if len(p) <= n - 1:
		p.sort(reverse=True)
		while len(p) < n - 1:
			p.append(1)
	if len(p) > n - 1:
		p.sort()
		while len(p) > n - 1:
			p[-2] = p[-2] % M * (p[-1] % M) % M
			p.pop()
		p.reverse()
	evc = [0 for __ in range(n)]
	dfs(1, n - 1, -1)
	evc.pop()
	evc.sort(reverse=True)
	ans = 0
	for i in range(n - 1):
		ans += evc[i] % M * (p[i] % M) % M
		ans = ans % M
	print(ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = 10 ** 9 + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var, end='\n'):
	sys.stdout.write(str(var) + end)

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(source=0, parent=-1):
	size[source] = 1
	for child in graph[source]:
		if child != parent:
			size[source] += (yield dfs(child, source))
	yield size[source]
for _ in range(int(data())):
	n = int(data())
	graph = [list() for i in range(n)]
	d = dict()
	for i in range(n - 1):
		(u, v) = sp()
		u -= 1
		v -= 1
		graph[u].append(v)
		graph[v].append(u)
		d[u, v] = d[v, u] = i
	size = [0] * n
	s = [0] * (n - 1)
	dfs()
	for i in range(1, n):
		s[i - 1] = size[i] * (n - size[i])
	s.sort()
	m = int(data())
	arr = l()
	if len(arr) < n - 1:
		arr += [1] * (n - 1 - len(arr))
	arr.sort()
	while len(arr) > n - 1:
		p = arr.pop()
		arr[-1] = arr[-1] * p % mod
	answer = 0
	for i in range(n - 1):
		answer += arr[i] * s[i]
		if answer > mod:
			answer %= mod
	out(answer)


t = int(input())
mod = 10 ** 9 + 7
from collections import deque

def pr(l):
	a = 1
	for i in l:
		a = a * i % mod
	return a

def dfs():
	ch = {i: 1 for i in range(n)}
	par = {i: -1 for i in range(n)}
	vis = [False for i in range(n)]
	s = deque([0])
	q = []
	while s:
		x = s.popleft()
		q.append(x)
		vis[x] = True
		for y in tr[x]:
			if vis[y]:
				continue
			s.append(y)
			par[y] = x
	for i in range(n - 1, 0, -1):
		ch[par[q[i]]] += ch[q[i]]
	l = [ch[i] * (n - ch[i]) for i in range(1, n)]
	l.sort()
	return l
for _ in range(t):
	n = int(input())
	tr = [[] for i in range(n)]
	for __ in range(n - 1):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		tr[u].append(v)
		tr[v].append(u)
	m = int(input())
	k = list(map(int, input().split()))
	k.sort()
	if m > n - 1:
		k = k[:n - 2] + [pr(k[n - 2:])]
	elif m < n - 1:
		k = [1 for ii in range(n - 1 - m)] + k
	z = dfs()
	ans = 0
	for i in range(n - 1):
		ans = (ans + z[i] * k[i]) % mod
	print(ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import heapq
MOD = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	n = int(input())
	adjacencyList = []
	adjacencyCount = []
	for _ in range(n):
		adjacencyList.append([])
		adjacencyCount.append(0)
	adjacencyCount[0] = 1
	motherVertex = [-1] * n
	descendentCount = [1] * n
	leafStack = []
	edgeNumber = []
	for _ in range(n - 1):
		(p, q) = map(int, input().split())
		adjacencyList[p - 1].append(q - 1)
		adjacencyList[q - 1].append(p - 1)
		adjacencyCount[p - 1] += 1
		adjacencyCount[q - 1] += 1
	treeStack = [(0, -1)]
	while treeStack:
		(vertex, mother) = treeStack.pop()
		motherVertex[vertex] = mother
		for elem in adjacencyList[vertex]:
			if elem != mother:
				treeStack.append((elem, vertex))
		if adjacencyCount[vertex] == 1:
			leafStack.append(vertex)
	while leafStack:
		elem = leafStack.pop()
		if elem == 0:
			continue
		edgeNumber.append(descendentCount[elem] * (n - descendentCount[elem]))
		descendentCount[motherVertex[elem]] += descendentCount[elem]
		adjacencyCount[motherVertex[elem]] -= 1
		if adjacencyCount[motherVertex[elem]] == 1:
			leafStack.append(motherVertex[elem])
	edgeNumber.sort()
	m = int(input())
	edgeWeight = []
	primeList = list(map(int, input().split()))
	primeList.sort()
	if n - 1 < m:
		for i in range(n - 1):
			edgeWeight.append(primeList[i])
		for i in range(n - 1, m):
			edgeWeight[n - 2] *= primeList[i]
			edgeWeight[n - 2] %= MOD
	else:
		for i in range(n - 1 - m):
			edgeWeight.append(1)
		for i in range(m):
			edgeWeight.append(primeList[i])
	ans = 0
	for i in range(n - 1):
		ans += edgeNumber[i] * edgeWeight[i]
		ans %= MOD
	print(ans)


mod = 1000000007
for _ in range(int(input())):
	n = int(input())
	routesges = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(u, v) = map(int, input().split())
		routesges[u].append([v, 0])
		routesges[v].append([u, 0])
	m = int(input())
	p = list(map(int, input().split()))
	p.sort(reverse=True)
	stack_1 = [[1, -1]]
	stack_2 = []
	while stack_1:
		(now, parent) = stack_1.pop()
		for i in range(len(routesges[now])):
			if routesges[now][i][0] != parent:
				stack_1.append([routesges[now][i][0], now])
				stack_2.append([routesges[now][i][0], now])
	routes = [0] * (n + 1)
	while stack_2:
		(to, fr_om) = stack_2.pop()
		routes[to] += 1
		routes[fr_om] += routes[to]
	routes = routes[2:]
	for i in range(n - 1):
		routes[i] *= n - routes[i]
	routes.sort(reverse=True)
	summa = 0
	if m > n - 1:
		for i in range(m - n + 2):
			routes[0] = routes[0] * p[i] % mod
		summa = routes[0]
		for i in range(1, n - 1):
			summa = (summa + routes[i] * p[i + m - n + 1]) % mod
		print(summa % mod)
	else:
		for i in range(m):
			summa = (summa + routes[i] * p[i]) % mod
		for i in range(m, n - 1):
			summa = (summa + routes[i]) % mod
		print(summa % mod)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
sys.setrecursionlimit(10 ** 5)
for _ in range(testCases):
	n = int(input())
	edges = [[] for i in range(n)]
	freqs = {}
	for _ in range(n - 1):
		(u, v) = input_split()
		u -= 1
		v -= 1
		edges[u].append(v)
		edges[v].append(u)
		freqs[min(u, v), max(u, v)] = 0
	m = int(input())
	primes = input_split()
	MOD = 10 ** 9 + 7
	primes.sort()
	touched = [False for i in range(n)]
	pending = [0]
	size = 1
	all_parents = [-1 for i in range(n)]
	all_sizes = [-1 for i in range(n)]
	descendants = [[] for i in range(n)]
	while len(pending) != 0:
		current = pending.pop()
		if current == -1:
			parent = pending.pop()
			size = 1
			for desc in descendants[parent]:
				size += all_sizes[desc]
			all_sizes[parent] = size
			u = all_parents[parent]
			v = parent
			if u == -1:
				continue
			mini = min(u, v)
			maxi = max(u, v)
			freqs[mini, maxi] = size * (n - size)
			continue
		touched[current] = True
		pending.append(current)
		pending.append(-1)
		for child in edges[current]:
			if not touched[child]:
				descendants[current].append(child)
				all_parents[child] = current
				pending.append(child)
	e_f = list(freqs.values())
	e_f.sort()
	if len(primes) <= len(e_f):
		primes = [1] * (len(e_f) - len(primes)) + primes
	else:
		front = primes[:len(e_f)]
		p = 1
		for i in range(len(e_f), len(primes)):
			p = p * primes[i] % MOD
		front[-1] *= p
		primes = front
	ans = 0
	for i in range(len(primes)):
		ans = (ans + primes[i] * e_f[i]) % MOD
	answers.append(ans)
print(*answers, sep='\n')


from collections import defaultdict
from collections import deque
t = int(input())
MOD = 1000000007
for _ in range(t):
	n = int(input())
	edge = defaultdict(list)
	for _ in range(n - 1):
		(a, b) = map(int, input().split())
		edge[a].append(b)
		edge[b].append(a)
	m = int(input())
	p = list(sorted(map(int, input().split())))
	if m < n - 1:
		p = [1] * (n - 1 - m) + p
	else:
		temp = []
		for u in p:
			if len(temp) < n - 1:
				temp.append(u)
			else:
				temp[-1] = temp[-1] * u % MOD
		p = temp
	(q, par, order) = (deque([1]), [0] * (n + 1), [])
	while q:
		u = q.popleft()
		order.append(u)
		for v in edge[u]:
			if v == par[u]:
				continue
			par[v] = u
			q.append(v)
	(lcc, ecc) = ([0] * (n + 1), [])
	for u in reversed(order):
		cc = 1
		for v in edge[u]:
			if v == par[u]:
				continue
			cc += lcc[v]
		lcc[u] = cc
		if u != 1:
			ecc.append(cc * (n - cc))
	ecc.sort()
	res = 0
	for i in range(len(p)):
		res = (res + ecc[i] * p[i]) % MOD
	print(res)


import sys
inp = sys.stdin.readline
mod = 10 ** 9 + 7

def solve():
	N = int(inp())
	d = [set() for _ in range(N + 1)]
	for i in range(N - 1):
		(u, v) = map(int, inp().split())
		d[u].add((v, i))
		d[v].add((u, i))
	G = [set() for _ in range(N + 1)]
	st = [2]
	vis = set([2])
	tp_sort = []
	while st:
		v = st.pop()
		tp_sort.append(v)
		for (u, i) in d[v]:
			if u in vis:
				continue
			G[v].add((u, i))
			vis.add(u)
			st.append(u)
	sz = [0] * (N + 1)
	cnt = [0] * (N - 1)
	for v in tp_sort[::-1]:
		cur = 1
		for (u, i) in G[v]:
			cur += sz[u]
			cnt[i] = sz[u] * (N - sz[u])
		sz[v] = cur
	M = int(inp())
	P = list(map(int, inp().split()))
	cnt.sort()
	cnt = cnt[::-1]
	if M <= N - 1:
		P.sort()
		P = P[::-1]
		for _ in range(N - 1 - M):
			P.append(1)
	else:
		P.sort()
		for _ in range(M - (N - 1)):
			p = P.pop()
			P[-1] = P[-1] * p % mod
		P = P[::-1]
	ans = 0
	for (c, p) in zip(cnt, P):
		ans = (ans + c * p) % mod
	print(ans)
for _ in range(int(input())):
	solve()


import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, Counter

def dfs(conn, path, n):
	st = [1]
	while len(st):
		if not path[st[-1]]:
			if len(st) >= 2:
				conn[st[-1]][st[-2]] = n - 1 - conn[st[-1]][-1]
				conn[st[-2]][st[-1]] = conn[st[-1]][-1] + 1
				conn[st[-2]][-1] += conn[st[-1]][-1] + 1
			st.pop()
			continue
		i = path[st[-1]].pop()
		path[i].remove(st[-1])
		st.append(i)

def main():
	mod = 10 ** 9 + 7
	for _ in range(int(input())):
		n = int(input())
		path = defaultdict(set)
		conn = defaultdict(Counter)
		for _ in range(n - 1):
			(u, v) = map(int, input().split())
			path[u].add(v)
			path[v].add(u)
		dfs(conn, path, n)
		for i in conn:
			del conn[i][-1]
		edge = []
		for i in sorted(conn.keys()):
			for j in conn[i]:
				if j > i:
					edge.append((n - conn[i][j]) * conn[i][j])
		r = sorted(edge, reverse=True)
		m = int(input())
		primes = sorted(list(map(int, input().split())), reverse=True)
		while len(primes) < n - 1:
			primes.append(1)
		val = 1
		fl = 0
		for i in range(max(0, m - n + 2)):
			fl = 1
			val *= primes[i]
			val %= mod
		if not fl:
			ans = r[0] * primes[0] % mod
		else:
			ans = val * r[0] % mod
		i = max(0, m - n + 1)
		for j in range(1, n - 1):
			ans += r[j] * primes[j + i] % mod
			ans %= mod
		print(ans % mod)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
from collections import deque
pprint = lambda s: print(' '.join(map(lambda x: str(x), s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
mod = 1000000007
for _ in range(int(input())):
	n = int(input())
	g = [[] for i in range(n)]
	for i in range(n - 1):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		g[a].append(b)
		g[b].append(a)
	k = int(input())
	lol = list(sorted(map(int, input().split())))
	if k < n - 1:
		lol = [1] * (n - 1 - k) + lol
	else:
		for i in range(k - n + 1):
			lol[-2] = lol[-1] * lol[-2] % mod
			del lol[-1]
	lvl = [-1 for i in range(n)]
	lvl[0] = 0
	bfs = deque()
	bfs.append(0)
	while bfs:
		v = bfs.popleft()
		for u in g[v]:
			if lvl[u] == -1:
				lvl[u] = lvl[v] + 1
				bfs.append(u)
	ver = [i for i in range(n)]
	ver.sort(key=lambda x: -lvl[x])
	under = [-1] * n
	ans = []
	for v in ver[:-1]:
		under[v] = 1
		for u in g[v]:
			if under[u] != -1:
				under[v] += under[u]
		ans.append(under[v] * (n - under[v]))
	ans.sort()
	ansv = 0
	for i in range(n - 1):
		ansv = (ansv + ans[-1 - i] * lol[-1 - i] % mod) % mod
	print(ansv)


import sys
import collections
input = sys.stdin.readline
mod = 10 ** 9 + 7
t = int(input())
for _ in range(t):
	n = int(input())
	g = [[] for _ in range(n + 1)]
	for _ in range(n - 1):
		(a, b) = map(int, input().split())
		g[a].append(b)
		g[b].append(a)
	q = collections.deque()
	q.append(1)
	checked = set()
	tracking = []
	while len(q) != 0:
		v = q.popleft()
		tracking.append(v)
		checked.add(v)
		for u in g[v]:
			if u not in checked:
				q.append(u)
	child = [1] * (n + 1)
	checked = set()
	edge_counts = []
	for v in tracking[::-1]:
		checked.add(v)
		for u in g[v]:
			if u not in checked:
				child[u] += child[v]
				edge_counts.append(child[v] * (n - child[v]))
	edge_counts = sorted(edge_counts, reverse=True)
	m = int(input())
	primes = list(map(int, input().split()))
	primes = sorted(primes, reverse=True)
	if m >= n:
		tmp = 1
		for i in range(m - n + 2):
			tmp *= primes[i]
			tmp %= mod
		tmp = [tmp]
		for i in range(m - n + 2, m):
			tmp.append(primes[i])
		primes = tmp
	else:
		for i in range(n - 1 - m):
			primes.append(1)
	ans = 0
	for i in range(n - 1):
		ans += edge_counts[i] * primes[i]
		ans %= mod
	print(ans)


import collections
for _ in range(int(input())):
	n = int(input())
	go = collections.defaultdict(set)
	for _ in range(n - 1):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		go[a].add(b)
		go[b].add(a)
	m = int(input())
	p = list(map(int, input().split()))
	p.sort()
	q = []
	for x in go:
		if len(go[x]) == 1:
			q.append(x)
	node = [1] * n
	while len(q) != 1:
		now = q.pop()
		parent = go[now].pop()
		node[parent] += node[now]
		go[parent].remove(now)
		if len(go[parent]) == 1:
			q.append(parent)
	for (i, x) in enumerate(node):
		node[i] = x * (n - x)
	node.sort()
	node = node[1:]
	while len(p) > n - 1:
		p[n - 2] = p.pop() * p[n - 2] % (10 ** 9 + 7)
	for i in range(-1, -len(p) - 1, -1):
		node[i] *= p[i]
	ans = sum(node) % (10 ** 9 + 7)
	print(ans)


def tInput():
	from sys import stdin
	input = stdin.readline
tInput()

def A():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		if n >= k:
			print(int(n % 2 != k % 2))
		else:
			print(k - n)

def B():
	for _ in range(int(input())):
		(x1, y1, z1) = map(int, input().split())
		(x2, y2, z2) = map(int, input().split())
		tot = 0
		p = min(x1, z2)
		x1 -= p
		z2 -= p
		tot += 2 * min(z1, y2)
		p = min(z1, y2)
		z1 -= p
		y2 -= p
		if z2 > 0:
			z2 -= min(z2, z1)
			tot -= 2 * min(y1, z2)
		print(tot)

def C():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		sa = sorted(a)
		m = min(a)
		w = True
		for i in range(n):
			if a[i] % m != 0:
				if a[i] != sa[i]:
					w = False
					break
		if w:
			print('YES')
		else:
			print('NO')

def D():
	t = int(input())
	from collections import deque
	for _ in range(t):
		n = int(input())
		graph = [set() for i in range(n + 1)]
		graph[1].add(0)
		queue = deque()
		numChildren = [0] * (n + 1)
		for i in range(n - 1):
			(u, v) = map(int, input().split())
			graph[u].add(v)
			graph[v].add(u)
		for i in range(1, n + 1):
			if len(graph[i]) == 1 and i != 1:
				queue.append(i)
		while len(queue) > 0:
			curr = queue.popleft()
			if curr == 1:
				break
			parent = graph[curr].pop()
			numChildren[curr] += 1
			numChildren[parent] += numChildren[curr]
			graph[parent].remove(curr)
			if len(graph[parent]) == 1:
				queue.append(parent)
		mults = [0] * (n - 1)
		for i in range(2, n + 1):
			mults[i - 2] = numChildren[i] * (n - numChildren[i])
		mults.sort()
		mod = 10 ** 9 + 7
		m = int(input())
		p = list(map(int, input().split()))
		if m <= n - 1:
			p = p + [1] * (n - m - 1)
			p.sort()
		else:
			p.sort()
			for i in range(n - 1, m):
				p[n - 2] = p[n - 2] * p[i] % mod
		tot = 0
		for i in range(n - 1):
			tot = (tot + p[i] * mults[i]) % mod
		print(tot)
D()


from functools import reduce

class Node:

	def __init__(self, val: int):
		self.val = val
		self.count = 1

def dfs(root, tree) -> int:
	n = len(tree) - 1
	visited = [False] * (n + 1)
	completed = [False] * (n + 1)
	stack = [root]
	while len(stack) > 0:
		node = stack[-1]
		if visited[node.val]:
			node.count += sum((child.count for child in tree[node.val] if completed[child.val]))
			stack.pop()
			completed[node.val] = True
		else:
			for child in tree[node.val]:
				if not visited[child.val]:
					stack.append(child)
			visited[node.val] = True
t = int(input())
while t > 0:
	n = int(input())
	tree = [[] for i in range(0, n + 1)]
	nodes = [Node(val) for val in range(0, n + 1)]
	for i in range(0, n - 1):
		(u, v) = map(int, input().split())
		tree[u].append(nodes[v])
		tree[v].append(nodes[u])
	m = int(input())
	factors = list(map(int, input().split()))
	m = len(factors)
	factors.sort(reverse=True)
	dfs(nodes[1], tree)
	edge_multipliers = [node.count * (n - node.count) for node in nodes if node.count != n and node.val != 0]
	edge_multipliers.sort(reverse=True)
	result = 0
	mod = int(1000000000.0 + 7)
	result = 0
	if m <= n - 1:
		for i in range(0, n - 1):
			p = edge_multipliers[i] % mod
			if i < m:
				p = factors[i] * p % mod
			result = (result + p) % mod
	else:
		p0 = 1
		for i in range(0, m - n + 2):
			p0 = p0 * factors[i] % mod
		factors = [p0] + factors[m - n + 2:m]
		for i in range(0, n - 1):
			result = (result + factors[i] * (edge_multipliers[i] % mod) % mod) % mod
	print(result)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys, threading
sys.setrecursionlimit(400000)
threading.stack_size(10 ** 8)

def dfs(x):
	global v, l1, adj, l, n
	v[x] = 1
	l1[x] = 1
	for i in adj[x]:
		if not v[i]:
			dfs(i)
			l1[x] += l1[i]
	l.append(l1[x] * (n - l1[x]))

def main():
	global v, l1, adj, l, n
	t = int(input())
	mod = 10 ** 9 + 7
	for i in range(t):
		n = int(input())
		adj = [[] for j in range(n + 1)]
		for j in range(n - 1):
			(x, y) = map(int, input().split())
			adj[x].append(y)
			adj[y].append(x)
		l = []
		v = [0] * (n + 1)
		l1 = [0] * (n + 1)
		m = int(input())
		p = list(map(int, input().split()))
		dfs(1)
		l.sort(reverse=True)
		p.sort(reverse=True)
		if m <= n - 1:
			for j in range(n - 1 - m):
				p.append(1)
		else:
			a = 1
			for j in range(m - n + 1):
				a *= p[j]
				a %= mod
			p = p[m - n + 1:]
			p[0] *= a
			p[0] %= mod
		ans = 0
		for j in range(n - 1):
			ans += l[j] * p[j]
			ans %= mod
		print(ans)
z = threading.Thread(target=main)
z.start()
z.join()