結果

問題 No.872 All Tree Path
ユーザー DaYuanChiDaYuanChi
提出日時 2021-01-28 00:00:30
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,251 bytes
コンパイル時間 1,768 ms
コンパイル使用メモリ 169,300 KB
実行使用メモリ 34,460 KB
最終ジャッジ日時 2023-09-07 06:49:35
合計ジャッジ時間 5,184 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 2 ms
5,384 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 AC 2 ms
5,388 KB
testcase_14 AC 2 ms
5,604 KB
testcase_15 AC 2 ms
5,612 KB
testcase_16 AC 2 ms
5,536 KB
testcase_17 AC 2 ms
5,424 KB
testcase_18 AC 2 ms
5,476 KB
testcase_19 AC 2 ms
5,404 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;

int depth[200005]; //depth[i]=頂点iの深さ
int par[200005];//par[i]=頂点iの親
int subtree_size[200005];//部分木のサイズ
int u[200005];
int v[200005];
int w[200005];

void dfs(Graph &G, int v, int p, int d){
  depth[v] = d;
  par[v] = p;
  for(auto nv : G[v]){
    if(nv==p)continue;
    dfs(G, nv, v, d+1);
  }
  // 帰りがけ時に、部分木サイズを求める
  subtree_size[v] = 1; // 自分自身
  for (auto c : G[v]) {
    if (c == p) continue;
    subtree_size[v] += subtree_size[c]; // 子のサイズを加える
  }
}
  
int main(){
  int n; cin >> n;
  Graph G(n);
  for(int i = 0; i < n-1; i++){ //木の辺の数はn-1
    int a, b, c; cin >> a >> b >> c;
    a--, b--;
    G[a].push_back(b);
    G[b].push_back(a);
    u[i] = a; v[i] = b; w[i] = c;
  }
  int root = 0; // 根を0に設定
  dfs(G, root, -1, 0);
  int ans = 0;
  for(int i = 0; i < n-1; i++){
    int num = 0; //num:根から遠い方の頂点を親とする部分木のサイズ
    if(depth[u[i]]>depth[v[i]]) num = subtree_size[u[i]];
    else num = subtree_size[v[i]];
    ans += w[i]*2*num*(n-num);
  }
  cout << ans << endl;
  return 0;
}
0