結果

問題 No.872 All Tree Path
ユーザー merom686merom686
提出日時 2019-08-31 00:52:03
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 66 ms / 3,000 ms
コード長 1,138 bytes
コンパイル時間 943 ms
コンパイル使用メモリ 79,440 KB
実行使用メモリ 13,136 KB
最終ジャッジ日時 2024-05-01 23:16:43
合計ジャッジ時間 2,132 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 61 ms
8,704 KB
testcase_01 AC 60 ms
8,704 KB
testcase_02 AC 60 ms
8,596 KB
testcase_03 AC 53 ms
13,136 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 61 ms
8,600 KB
testcase_06 AC 63 ms
8,696 KB
testcase_07 AC 66 ms
8,704 KB
testcase_08 AC 7 ms
5,376 KB
testcase_09 AC 8 ms
5,376 KB
testcase_10 AC 7 ms
5,376 KB
testcase_11 AC 7 ms
5,376 KB
testcase_12 AC 7 ms
5,376 KB
testcase_13 AC 1 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 2 ms
5,376 KB
testcase_17 AC 2 ms
5,376 KB
testcase_18 AC 1 ms
5,376 KB
testcase_19 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

ll r = 0;

struct Graph {
    struct Vertex { int n; };
    struct Edge { int i, n, c; };
    Graph(int n, int m) : v(n, { -1 }), e(m), n(n), m(0) {}
    void add_edge(int i, int j, int c) {
        e[m] = { j, v[i].n, c };
        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;
            int l = dfs(o.i, i);
            r += (ll)l * (n - l) * o.c;
            k += l;
        }
        return 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, c;
        cin >> a >> b >> c;
        a--; b--;

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

    g.dfs(0, -1);

    cout << r * 2 << endl;

    return 0;
}
0