import sys import collections class Node: def __init__(self, index): self.index = index self.neighbors = [] self.children = [] self.parent = None self.parentWeight = 0 def isLeaf(self): return (len(self.children) == 0) def readNT(): N,T = map(int, sys.stdin.readline().strip().split()) return N,T def readNodes(N): nodes = [] for i in range(N): nodes.append(Node(i)) for i in range(N-1): A,B,C = map(int, sys.stdin.readline().strip().split()) nodes[A-1].neighbors.append((B-1, C)) nodes[B-1].neighbors.append((A-1, C)) return nodes def rootTree(nodes): tree = nodes[0] seen = set() seen.add(0) deq = collections.deque() deq.append(tree) while deq: node = deq.pop() for c,cost in node.neighbors: if c in seen: node.parent = c node.parentWeight = cost else: node.children.append(c) seen.add(c) deq.append(nodes[c]) def readTasks(T): for i in range(T): K = int(sys.stdin.readline()) xs = map(int, sys.stdin.readline().strip().split()) counts = collections.defaultdict(int) for x in xs: counts[x-1] += 1 yield K, counts def solveTask(task): K, counts = task childCounts = {} deq = collections.deque() for n in nodes: childCounts[n.index] = len(n.children) if n.isLeaf(): deq.append(n) total = 0 while deq: node = deq.pop() if (node.parent is None): break # print node.index,":",counts[node.index],(K-counts[node.index]),node.parentWeight total += counts[node.index]*(K-counts[node.index])*node.parentWeight counts[node.parent] += counts[node.index] childCounts[node.parent] -= 1 if (childCounts[node.parent] == 0): deq.append(nodes[node.parent]) print total def solveTasks(tasks): Ks = [] countss = collections.defaultdict(collections.Counter) for t, (K, counts) in enumerate(tasks): Ks.append(K) for x, count in counts.items(): countss[x][t] += count childCounts = {} deq = collections.deque() for n in nodes: childCounts[n.index] = len(n.children) if n.isLeaf(): deq.append(n) totals = [0 for _ in tasks] while deq: node = deq.pop() if (node.parent is None): break for t, count in countss[node.index].items(): # print t, node.index, ":", count, (Ks[t]-count), node.parentWeight totals[t] += count * (Ks[t]-count)*node.parentWeight countss[node.parent][t] += count childCounts[node.parent] -= 1 if (childCounts[node.parent] == 0): deq.append(nodes[node.parent]) del countss[node.index] for total in totals: print total N,T = readNT() nodes = readNodes(N) rootTree(nodes) tasks = list(readTasks(T)) #tasks = tasks[:10000] solveTasks(tasks)