結果

問題 No.872 All Tree Path
ユーザー Y17
提出日時 2019-08-30 23:05:52
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 344 ms / 3,000 ms
コード長 1,058 bytes
コンパイル時間 1,295 ms
コンパイル使用メモリ 161,912 KB
実行使用メモリ 50,176 KB
最終ジャッジ日時 2024-11-22 02:38:24
合計ジャッジ時間 5,042 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

#define int long long

vector<pair<int, int>> graph[200010];
vector<pair<int, int>> tree[200010];


int used[200010] = {};

void make_tree(int idx){
    used[idx] = 1;
    for(int i = 0;i < graph[idx].size();i++){
        int child = graph[idx][i].first;
        if(!used[child]){
            tree[idx].push_back({child, graph[idx][i].second});
            make_tree(child);

        }
    }
}

int memo[200010];
int n;

int dp(int idx){
    int ans = 0;
    int num = 1;

    for(int i = 0;i < tree[idx].size();i++){
        int child = tree[idx][i].first;
        ans += dp(child);
        num += memo[child];
        ans += (memo[child] * (n-memo[child]) * tree[idx][i].second) * 2;
    }

    memo[idx] = num;
    return ans;
}

signed main(){
    cin >> n;

    for(int i = 0;i < n-1;i++){
        int a, b, c;
        cin >> a >> b >> c;
        a--;
        b--;
        graph[a].push_back({b, c});
        graph[b].push_back({a, c});
    }

    make_tree(0);

    cout << dp(0) << endl;
    return 0;
}
0