#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } const long long MAX = 5100000; const long long INF = 1LL << 60; const long long mod = 1000000007LL; //const long long mod = 998244353LL; using namespace std; typedef unsigned long long ull; typedef long long ll; ll N; vector> ug; vector>> wg; vector sum; vector ord; ll now; ll clz(ll x) { for (ll i = 31; i >= 0; i--) { if ((x >> i) & 1) { return 31 - i; } } } template< typename G > struct DoublingLowestCommonAncestor { const int LOG; vector< int > dep; const G& g; vector< vector< int > > table; DoublingLowestCommonAncestor(const G& g) : g(g), dep(g.size()), LOG(32 - clz(g.size())) { table.assign(LOG, vector< int >(g.size(), -1)); } void dfs(int idx, int par, int d) { table[0][idx] = par; dep[idx] = d; for (auto& to : g[idx]) { if (to != par) dfs(to, idx, d + 1); } } void build() { dfs(0, -1, 0); for (int k = 0; k + 1 < LOG; k++) { for (int i = 0; i < table[k].size(); i++) { if (table[k][i] == -1) table[k + 1][i] = -1; else table[k + 1][i] = table[k][table[k][i]]; } } } int query(int u, int v) { if (dep[u] > dep[v]) swap(u, v); for (int i = LOG - 1; i >= 0; i--) { if (((dep[v] - dep[u]) >> i) & 1) v = table[i][v]; } if (u == v) return u; for (int i = LOG - 1; i >= 0; i--) { if (table[i][u] != table[i][v]) { u = table[i][u]; v = table[i][v]; } } return table[0][u]; } }; void dfs(ll cur, ll pre) { ord[cur] = now; now++; for (auto next : wg[cur]) { if (next.first == pre) continue; sum[next.first] = sum[cur] + next.second; dfs(next.first, cur); } } int main() { /* cin.tie(nullptr); ios::sync_with_stdio(false); */ scanf("%lld", &N); ug.resize(N), wg.resize(N); ord = vector(N); for (ll i = 0; i < N - 1; i++) { ll x, y, w; scanf("%lld %lld %lld", &x, &y, &w); ug[x].push_back(y); ug[y].push_back(x); wg[x].emplace_back(y, w); wg[y].emplace_back(x, w); } sum = vector(N); dfs(0, -1); DoublingLowestCommonAncestor>> lca(ug); lca.build(); ll Q; scanf("%lld", &Q); while (Q--) { ll k; scanf("%lld", &k); vector> vp(k); for (ll i = 0; i < k; i++) { scanf("%lld", &vp[i].second); vp[i].first = ord[vp[i].second]; } sort(vp.begin(), vp.end()); ll res = 0; for (ll i = 0; i < k; i++) { ll p = lca.query(vp[i].second, vp[(i + 1) % k].second); res += sum[vp[i].second] + sum[vp[(i + 1) % k].second] - sum[p] * 2; } res /= 2; printf("%lld\n", res); } return 0; }