結果

問題 No.1098 LCAs
ユーザー merom686merom686
提出日時 2020-06-26 22:17:17
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 102 ms / 2,000 ms
コード長 1,321 bytes
コンパイル時間 815 ms
コンパイル使用メモリ 90,332 KB
実行使用メモリ 15,108 KB
最終ジャッジ日時 2023-09-18 05:29:50
合計ジャッジ時間 3,978 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 2 ms
4,376 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 1 ms
4,380 KB
testcase_13 AC 2 ms
4,376 KB
testcase_14 AC 2 ms
4,376 KB
testcase_15 AC 2 ms
4,380 KB
testcase_16 AC 2 ms
4,376 KB
testcase_17 AC 2 ms
4,380 KB
testcase_18 AC 89 ms
9,296 KB
testcase_19 AC 83 ms
9,476 KB
testcase_20 AC 89 ms
9,376 KB
testcase_21 AC 91 ms
9,364 KB
testcase_22 AC 88 ms
9,312 KB
testcase_23 AC 64 ms
9,248 KB
testcase_24 AC 68 ms
9,540 KB
testcase_25 AC 63 ms
9,264 KB
testcase_26 AC 70 ms
9,296 KB
testcase_27 AC 66 ms
9,368 KB
testcase_28 AC 102 ms
14,820 KB
testcase_29 AC 100 ms
15,108 KB
testcase_30 AC 99 ms
14,540 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;

struct Graph {
    struct Vertex { int n, k; ll r; };
    struct Edge { int i, n; };
    Graph(int n, int m) : v(n, { -1, -1, -1 }), e(m), n(n), m(0) {}
    void add_edge(int i, int j) {
        e[m] = { j, v[i].n };
        v[i].n = m;
        m++;
    }
    int dfs(int i, int p) {
        int k = 1;
        for (int j = v[i].n; j >= 0; j = e[j].n) {
            Edge& o = e[j];
            if (o.i == p) continue;
            k += dfs(o.i, i);
        }
        ll r = k;
        for (int j = v[i].n; j >= 0; j = e[j].n) {
            Edge& o = e[j];
            if (o.i == p) continue;
            r += (ll)(k - v[o.i].k) * v[o.i].k;
        }
        v[i].r = r;
        return v[i].k = k;
    }
    vector<Vertex> v;
    vector<Edge> e;
    int n, m;
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;

    Graph g(n, (n - 1) * 2);
    for (int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--; b--;

        g.add_edge(a, b);
        g.add_edge(b, a);
    }

    g.dfs(0, -1);

    for (int i = 0; i < n; i++) {
        cout << g.v[i].r << '\n';
    }

    return 0;
}
0