1 #include<cstring>
2 #include<iostream>
3 #include<cstdio>
4 #include<algorithm>
5 #include<cstdlib>
6 using namespace std;
7
8 typedef long long ll;
9 #define maxn (250010)
10 #define inf (1LL<<60)
11 int n,m,cnt,side[maxn],next[maxn*2],dep[maxn],h[maxn],st[maxn],sign[maxn];
12 int toit[maxn*2],cost[maxn*2],f[maxn][30],id[maxn],ID;
13 ll g[maxn],best[maxn];
14
15 inline int read()
16 {
17 int x=0,f=1;char ch=getchar();
18 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
19 while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
20 return x*f;
21 }
22
23 inline bool cmp(int a,int b) { return id[a] < id[b]; }
24
25 inline void add(int a,int b,int c)
26 {
27 next[++cnt] = side[a]; side[a] = cnt;
28 toit[cnt] = b; cost[cnt] = c;
29 }
30
31 inline void ins(int a,int b,int d)
32 {
33 if (a == b) return;
34 if (sign[a] != d) side[a] = 0,sign[a] = d;
35 if (sign[b] != d) side[b] = 0,sign[b] = d;
36 next[++cnt] = side[a]; side[a] = cnt; toit[cnt] = b;
37 }
38
39 inline void dfs(int now)
40 {
41 id[now] = ++ID;
42 for (int i = 1;1 << i <= dep[now];++i)
43 f[now][i] = f[f[now][i-1]][i-1];
44 for (int i = side[now];i;i = next[i])
45 if (toit[i] != f[now][0])
46 {
47 best[toit[i]] = min(best[now],(ll)cost[i]);
48 dep[toit[i]] = dep[now] + 1;
49 f[toit[i]][0] = now;
50 dfs(toit[i]);
51 }
52 }
53
54 inline void jump(int &a,int step)
55 {
56 int i = 0;
57 for (;step;step >>= 1,++i) if (step&1) a = f[a][i];
58 }
59
60 inline int lca(int a,int b)
61 {
62 if (dep[a]<dep[b]) swap(a,b);
63 jump(a,dep[a]-dep[b]);
64 if (a == b) return a;
65 for (int i = 0;i >= 0;)
66 {
67 if (f[a][i] != f[b][i]) a = f[a][i],b = f[b][i],++i;
68 else --i;
69 }
70 return f[a][0];
71 }
72
73 inline void dp(int now)
74 {
75 g[now] = best[now];
76 ll tmp = 0;
77 for (int i = side[now];i;i = next[i])
78 dp(toit[i]),tmp += g[toit[i]];
79 if (tmp && tmp <= g[now]) g[now] = tmp;
80 }
81
82 inline void work(int p)
83 {
84 cnt = 0;
85 int K = read(),tot,top;
86 for (int i = 1;i <= K;++i) h[i] = read();
87 sort(h+1,h+K+1,cmp);
88 h[tot = 1] = h[1];
89 for (int i = 2;i <= K;++i) if (lca(h[tot],h[i]) != h[tot]) h[++tot] = h[i];
90 st[top = 1] = 1;
91 for (int i = 1;i <= tot;++i)
92 {
93 int ans = lca(h[i],st[top]);
94 while (true)
95 {
96 if (dep[ans] >= dep[st[top-1]])
97 {
98 ins(ans,st[top--],p);
99 break;
100 }
101 ins(st[top-1],st[top],p); --top;
102 }
103 if (st[top] != ans) st[++top] = ans;
104 if (st[top] != h[i]) st[++top] = h[i];
105 }
106 while (--top) ins(st[top],st[top+1],p);
107 dp(1);
108 printf("%lld\n",g[1]);
109 }
110
111 int main()
112 {
113 freopen("2286.in","r",stdin);
114 freopen("2286.out","w",stdout);
115 scanf("%d",&n);
116 for (int i = 1;i < n;++i)
117 {
118 int a = read(),b = read(),c = read();
119 add(a,b,c); add(b,a,c);
120 }
121 dep[0] = -1; best[1] = inf; dfs(1);
122 scanf("%d",&m);
123 for (int i = 1;i <= m;++i) work(i);
124 fclose(stdin); fclose(stdout);
125 return 0;
126 }