結果

問題 No.872 All Tree Path
ユーザー DaYuanChiDaYuanChi
提出日時 2021-01-28 00:02:42
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 283 ms / 3,000 ms
コード長 1,257 bytes
コンパイル時間 1,552 ms
コンパイル使用メモリ 169,984 KB
実行使用メモリ 34,256 KB
最終ジャッジ日時 2023-09-07 06:51:00
合計ジャッジ時間 4,961 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 266 ms
18,684 KB
testcase_01 AC 283 ms
18,812 KB
testcase_02 AC 265 ms
18,684 KB
testcase_03 AC 192 ms
34,256 KB
testcase_04 AC 2 ms
5,452 KB
testcase_05 AC 264 ms
18,712 KB
testcase_06 AC 263 ms
18,732 KB
testcase_07 AC 260 ms
18,796 KB
testcase_08 AC 20 ms
6,484 KB
testcase_09 AC 20 ms
6,340 KB
testcase_10 AC 20 ms
6,412 KB
testcase_11 AC 20 ms
6,348 KB
testcase_12 AC 20 ms
6,412 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 2 ms
5,368 KB
testcase_15 AC 2 ms
5,452 KB
testcase_16 AC 2 ms
5,412 KB
testcase_17 AC 2 ms
5,412 KB
testcase_18 AC 2 ms
5,488 KB
testcase_19 AC 3 ms
5,456 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);
  ll ans = 0;
  for(int i = 0; i < n-1; i++){
    ll num = 0; //num:根から遠い方の頂点を親とする部分木のサイズ
    if(depth[u[i]]>depth[v[i]]) num = (ll)subtree_size[u[i]];
    else num = subtree_size[v[i]];
    ans += w[i]*2*num*((ll)n-num);
  }
  cout << ans << endl;
  return 0;
}
0