#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define F(i, x, y) for (int i = x; i <= y; ++i)
#define U(i, y, x) for (int i = y; i >= x; --i)
#define pbk push_back
#define mkp make_pair
#define fst first
#define sec second
namespace IO{
template <typename T> inline void read(T &x) {
x = 0; bool w = 1; char ch = getchar();
while (!isdigit(ch)) {
if (ch == 0x2d) w = 0;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 1) + (x << 3) + (ch ^ 0x30);
ch = getchar();
} x = w ? x : -x;
}
template <typename T> inline void write(T x) {
if (x < 0) putchar(0x2d), x = -x;
if (x > 9) write(x / 0xa);
putchar(x % 0xa + 0x30);
}
} using namespace IO;
#define N 250005
#define M 500005
const LL INF = 1e18; // INF要开大
int n, m, k, h[N];
vector<pair<int, LL> > e[N];
vector<int> E[N];
int dfn[N], tim, fa[N][20], dep[N]; LL w[N];
inline void dfs(int x, int father) {
dfn[x] = ++tim; fa[x][0] = father; dep[x] = dep[father] + 1;
F(i, 0, 18) fa[x][i + 1] = fa[fa[x][i]][i];
F(i, 0, (int) e[x].size() - 1) {
int y = e[x][i].fst; if (y == father) continue;
w[y] = min(w[x], e[x][i].sec); dfs(y, x);
}
}
inline int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
U(i, 19, 0) if (dep[fa[x][i]] >= dep[y]) x = fa[x][i];
if (x == y) return x;
U(i, 19, 0) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
inline bool cmp(const int x, const int y) {
return dfn[x] < dfn[y];
}
int a[N << 1], tot, vis[N];
inline void connect(int x, int y) {
E[x].pbk(y);
}
inline void build() {
sort(h + 1, h + k + 1, cmp);
a[tot = 1] = 1;
F(i, 1, k - 1) {
a[++tot] = h[i];
a[++tot] = lca(h[i], h[i + 1]);
} a[++tot] = h[k];
sort(a + 1, a + tot + 1, cmp);
tot = unique(a + 1, a + tot + 1) - a - 1; // 未去重时有2k个点,a数组空间要开2N
F(i, 1, tot - 1) connect(lca(a[i], a[i + 1]), a[i + 1]);
}
inline void clean() {
F(i, 1, tot) E[a[i]].clear();
F(i, 1, k) vis[h[i]] = 0;
}
inline LL dp(int x) {
if (vis[x]) return w[x];
LL tmp = 0;
F(i, 0, (int) E[x].size() - 1) {
tmp+= dp(E[x][i]);
} return min(w[x], tmp);
}
void init() {
read(n); int x, y; LL z;
F(i, 2, n) {
read(x), read(y), read(z);
e[x].pbk(mkp(y, z));
e[y].pbk(mkp(x, z));
}
w[1] = INF;
dfs(1, 0);
}
void work() {
read(m);
F(i, 1, m) {
read(k); F(i, 1, k) read(h[i]);
build(); F(i, 1, k) vis[h[i]] = 1;
write(dp(1)); putchar(0xa);
clean();
}
}
int main() {
init(); work();
return 0;
}剪贴板
剪贴板 2d51jqp4
剪贴板信息
剪贴板信息
- 收录
- 更新