1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include <cstdio> #include <cctype> #include <cstring> #include <algorithm> using namespace std;
template<typename T>inline void read(T &x) {} template<typename TT> inline void print(TT x, char end = '\n') {}
typedef long long LL;
const int N = 25e4 + 9;
struct Edge { int nxt, to, val; };
int n, m, cnt_e, dfu; int head[N], pu[N], po[N], fa[N][20], deep[N], mn[N], a[N<<1], stk[N]; LL f[N]; bool vis[N]; Edge e[N<<1];
inline void add_edge(int u, int v, int w) { e[++cnt_e] = (Edge){head[u], v, w}, head[u] = cnt_e; }
void dfs(int u, int last) { pu[u] = ++dfu; deep[u] = deep[last] + 1; fa[u][0] = last; for (int i = 1; 1 << i <= deep[u]; ++i) fa[u][i] = fa[fa[u][i-1]][i-1]; for (int i = head[u], v; i; i = e[i].nxt) if ((v = e[i].to) != last) { mn[v] = min(mn[u], e[i].val); dfs(v, u); } po[u] = ++dfu; }
int LCA(int x, int y) { if (deep[x] < deep[y]) swap(x, y); for (int i = 19; ~i; --i) if (deep[fa[x][i]] >= deep[y]) x = fa[x][i]; for (int i = 19; ~i; --i) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return x == y ? x : fa[x][0]; }
inline bool cmp(int x, int y) { return (x > 0 ? pu[x] : po[-x]) < (y > 0 ? pu[y] : po[-y]); }
int main() { read(n); for (int i = 1, u, v, w; i < n; ++i) read(u), read(v), read(w), add_edge(u, v, w), add_edge(v, u, w); mn[1] = 0x7fffffff; dfs(1, 0); read(m); int k, tot, top; while (m--) { tot = top = 0; read(k); for (int i = 1; i <= k; ++i) read(a[++tot]), vis[a[tot]] = true, f[a[tot]] = mn[a[tot]]; sort(a+1, a+k+1, cmp); for (int i = 1, lca; i < k; ++i){ lca = LCA(a[i], a[i+1]); if (!vis[lca]) a[++tot] = lca, vis[lca] = true; } if (!vis[1]) a[++tot] = 1; k = tot; for (int i = 1; i <= k; ++i) a[++tot] = -a[i]; sort(a+1, a+tot+1, cmp); for (int i = 1, u; i <= tot; ++i) { if (a[i] > 0) stk[++top] = a[i]; else { u = stk[top--]; if (u != 1) f[stk[top]] += min(f[u], (LL)mn[u]); else print(f[u]); f[u] = vis[u] = 0; } } } return 0; }
|