#include #include #include #include #include #include #include #include #include #include using namespace std; #define MOD 1000000007 #define INF (1<<29) #define LINF (1LL<<60) #define EPS (1e-10) typedef long long Int; typedef pair P; Int ppp; Int come[108000]; Int p[108000][20]; Int depth[108000]; Int node[108000]; Int weight[108000]; vector

edge[108000]; void dfs(Int x, Int last = -1, Int d = 0){ come[x] = ppp; node[ppp] = x; depth[x] = d; ppp++; for(auto p:edge[x]){ Int to = p.first, w = p.second; if(to == last)continue; weight[to] = weight[x] + w; dfs(to, x, d + 1); } if(last != -1){ for(Int i = 0;i < 20;i++){ if(i == 0)p[x][i] = last; else p[x][i] = p[p[x][i-1]][i-1]; } } } Int la(Int x, Int d, Int pp = 19){ if(d == 0)return x; while((d & (1 << pp)) == 0)pp--; x = p[x][pp]; return la(x, d - (1 << pp), pp); } Int lca(Int x, Int y){ if(depth[x] < depth[y])swap(x, y); if(depth[x] > depth[y])x = la(x, depth[x] - depth[y]); if(x == y)return x; Int up = 19; while(p[x][0] != p[y][0]){ while(p[x][up] == p[y][up])up--; x = p[x][up]; y = p[y][up]; } return p[x][0]; } void solve(){ Int k, ans = 0; cin >> k; vector nodes; for(Int i = 0;i < k;i++){ Int x; cin >> x; nodes.push_back(come[x]); } sort(nodes.begin(), nodes.end()); for(Int i = 0;i < k;i++){ Int x = node[nodes[i]]; Int y = node[nodes[(i+1)%k]]; Int l = lca(x, y); //cout << x << ":" << weight[x] << " " << y << ":" << weight[y] << " " << l << ":" << weight[l] << endl; ans += weight[x] - weight[l]; ans += weight[y] - weight[l]; } cout << ans / 2 << endl; } int main(){ int n, u, v, w, q; cin >> n; for(Int i = 0;i < n-1;i++){ cin >> u >> v >> w; edge[u].push_back(P(v,w)); edge[v].push_back(P(u,w)); } dfs(0); cin >> q; while(q--)solve(); return 0; }