結果

問題 No.901 K-ary εxtrεεmε
コンテスト
ユーザー zelda_master
提出日時 2026-09-21 00:22:40
言語 C++14
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -lm -std=c++14 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
WA  
実行時間 -
コード長 1,828 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 350 ms
コンパイル使用メモリ 82,336 KB
実行使用メモリ 19,424 KB
最終ジャッジ日時 2026-09-21 00:22:46
合計ジャッジ時間 5,232 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge3_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 4 WA * 25
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <iostream>
#include <cstring>
#include <cstdio>
#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];

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) {
    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][0] != anc[v][0]) 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);
        }
        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;
}
0