結果
| 問題 | No.901 K-ary εxtrεεmε |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2026-09-21 00:35:26 |
| 言語 | C++14 (gcc 15.3.0 + boost 1.92.0 + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 52 ms / 3,000 ms |
| + 810µs | |
| コード長 | 1,990 bytes |
| 記録 | |
| コンパイル時間 | 457 ms |
| コンパイル使用メモリ | 93,556 KB |
| 実行使用メモリ | 19,984 KB |
| 最終ジャッジ日時 | 2026-09-21 00:35:35 |
| 合計ジャッジ時間 | 5,798 ms |
|
ジャッジサーバーID (参考情報) |
judge3_0 / judge1_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 29 |
ソースコード
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long LL;
const int N = 100010, M = 2 * N, L = 20;
LL ww[N];
int n, q, h[N], e[M], ne[M], w[M], idx, anc[N][L], dep[N], dfn[N], cnt;
void Add(int x, int y, int z) {
e[idx] = y, w[idx] = z, ne[idx] = h[x], h[x] = idx++;
}
void DFS(int u, int p) {
dfn[u] = ++cnt;
dep[u] = dep[p] + 1, anc[u][0] = p;
for (int i = 1; i < L; ++i) anc[u][i] = anc[anc[u][i - 1]][i - 1];
for (int i = h[u]; i != -1; i = ne[i]) {
int v = e[i];
if (v == p) continue;
ww[v] = ww[u] + w[i];
DFS(v, u);
}
}
int LCA(int u, int v) {
if (dep[u] < dep[v]) swap(u, v);
int d = dep[u] - dep[v];
for (int i = 0; i < L; ++i) {
if (d >> i & 1) u = anc[u][i];
}
if (u == v) return u;
for (int i = L - 1; i >= 0; --i) {
if (anc[u][i] != anc[v][i]) u = anc[u][i], v = anc[v][i];
}
return anc[u][0];
}
int main() {
scanf("%d", &n);
memset(h, -1, sizeof(h));
for (int i = 1, x, y, z; i <= n - 1; ++i) {
scanf("%d%d%d", &x, &y, &z);
++x, ++y;
Add(x, y, z), Add(y, x, z);
}
DFS(1, 0);
scanf("%d", &q);
while (q--) {
int len;
scanf("%d", &len);
vector<int> vec;
for (int i = 1, x; i <= len; ++i) {
scanf("%d", &x);
++x;
vec.push_back(x);
}
sort(vec.begin(), vec.end(), [](int i1, int i2) {
return dfn[i1] < dfn[i2];
});
LL ans = 0LL;
for (int i = 1; i < vec.size(); ++i) {
// vec[i - 1] -> vec[i]
int x = vec[i - 1], y = vec[i];
int lca = LCA(x, y);
ans += ww[x] + ww[y] - 2 * ww[lca];
}
int x = vec.back(), y = vec.front();
int lca = LCA(x, y);
ans += ww[x] + ww[y] - 2 * ww[lca];
printf("%lld\n", ans / 2);
}
return 0;
}