#include
using namespace std;
struct edge { int t, v; edge *next; };
typedef long long dint; #ifdef WIN32 #define lld “%I64d” #else #define lld “%lld” #endif #define _l (long long int)
const int maxn = 250009; const int maxl = 19; const int inf = 0x3f3f3f3f; const dint dinf = 0x3f3f3f3f3f3f3f3fll;
int n, m; int d[maxn], dfb[maxn], dfe[maxn], dfo[maxn]; int ut[maxn][maxl], uv[maxn][maxl]; edge ebuf_arr[maxn « 1], *ebuf(ebuf_arr), *head[maxn];
inline void addEdge(int u, int v, int w) { ebuf-> t = v; ebuf-> v = w; ebuf-> next = head[u]; head[u] = ebuf ++; }
void buildTree() { static int stc[maxn]; int tst(1), dfn(0); memset(d, 0, sizeof(d)); d[stc[tst] = 1] = 1; while (tst) { int p(stc[tst –]); dfo[dfb[p] = ++ dfn] = p; dfe[p] = dfb[p]; for (int i = 1; i < maxl; ++ i) { ut[p][i] = ut[ut[p][i - 1]][i - 1]; uv[p][i] = min(uv[p][i - 1], uv[ut[p][i - 1]][i - 1]); } for (edge* e = head[p]; e; e = e-> next) if (!d[e-> t]) { d[e-> t] = d[p] + 1; ut[e-> t][0] = p; uv[e-> t][0] = e-> v; stc[++ tst] = e-> t; } } for (int i = n; i > 1; – i) { int p(dfo[i]), f(ut[p][0]); if (dfe[f] < dfe[p]) dfe[f] = dfe[p]; } }
inline bool cmpDfn(const int& a, const int& b) { return dfb[a] < dfb[b]; }
int LCA(int u, int v) { if (d[u] < d[v]) swap(u, v); for (int i = maxl - 1; i >= 0; – i) if (d[ut[u][i]] >= d[v]) u = ut[u][i]; if (u == v) return u; for (int i = maxl - 1; i >= 0; – i) if (ut[u][i] != ut[v][i]) { u = ut[u][i]; v = ut[v][i]; } return ut[u][0]; } int minVal(int u, int dx) { int ans(inf); for (int i = maxl - 1; i >= 0; – i) if (d[ut[u][i]] >= dx) { ans = min(ans, uv[u][i]); u = ut[u][i]; } return ans; }
dint f[maxn]; inline void upF(int u, int a) { f[u] = min(f[u], _l minVal(u, d[a])); } dint DP() { static int stc[maxn], q[maxn]; int t, tst(1); scanf("%d", &t); for (int i = 0; i < t; ++ i) scanf("%d", q + i); sort(q, q + t, cmpDfn); f[stc[1] = 1] = 0; for (int i = 0; i < t; ++ i) { int p(q[i]), a(LCA(p, stc[tst])); if (a == stc[tst]) { if (p != stc[tst]) { stc[++ tst] = p; f[p] = dinf; } } else if (a == p) { while (d[stc[tst]] > d[p]) { upF(stc[tst], stc[tst - 1]); f[stc[tst - 1]] += f[stc[tst]]; – tst; } if (p != stc[tst]) { stc[++ tst] = p; f[p] = 0; } else f[p] = dinf; } else { while (d[stc[tst - 1]] >= d[a]) { upF(stc[tst], stc[tst - 1]); f[stc[tst - 1]] += f[stc[tst]]; – tst; } if (d[stc[tst]] > d[a]) { upF(stc[tst], a); f[a] = f[stc[tst]]; stc[tst] = a; } stc[++ tst] = p; f[p] = dinf; } } while (tst > 1) { upF(stc[tst], stc[tst - 1]); f[stc[tst - 1]] += f[stc[tst]]; – tst; } return f[1]; }
int main() { #ifndef ONLINE_JUDGE freopen(".in", “r”, stdin); #endif
scanf("%d", &n);
for (int i = 1; i < n; ++ i) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
addEdge(u, v, w);
addEdge(v, u, w);
}
buildTree();
scanf("%d", &m);
while (m --)
printf(lld "\n", DP());
}