結果

問題 No.872 All Tree Path
ユーザー tnakao0123tnakao0123
提出日時 2019-09-04 17:42:03
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 148 ms / 3,000 ms
コード長 1,587 bytes
コンパイル時間 1,244 ms
コンパイル使用メモリ 90,864 KB
実行使用メモリ 19,020 KB
最終ジャッジ日時 2023-08-28 09:11:29
合計ジャッジ時間 4,391 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 148 ms
19,020 KB
testcase_01 AC 142 ms
18,860 KB
testcase_02 AC 136 ms
18,808 KB
testcase_03 AC 79 ms
17,628 KB
testcase_04 AC 4 ms
9,308 KB
testcase_05 AC 145 ms
18,888 KB
testcase_06 AC 145 ms
18,920 KB
testcase_07 AC 138 ms
18,976 KB
testcase_08 AC 13 ms
10,292 KB
testcase_09 AC 13 ms
10,296 KB
testcase_10 AC 13 ms
10,172 KB
testcase_11 AC 14 ms
10,252 KB
testcase_12 AC 13 ms
10,340 KB
testcase_13 AC 4 ms
9,184 KB
testcase_14 AC 4 ms
9,316 KB
testcase_15 AC 4 ms
9,312 KB
testcase_16 AC 4 ms
9,172 KB
testcase_17 AC 4 ms
9,252 KB
testcase_18 AC 4 ms
9,228 KB
testcase_19 AC 4 ms
9,356 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

/* -*- coding: utf-8 -*-
 *
 * 872.cc:  No.872 All Tree Path - yukicoder
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 200000;

/* typedef */

typedef long long ll;
typedef queue<int> qi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;

/* global variables */

vpii nbrs[MAX_N];
int cns[MAX_N], ps[MAX_N], pws[MAX_N], ss[MAX_N];

/* subroutines */

/* main */

int main() {
  int n;
  scanf("%d", &n);

  for (int i = 1; i < n; i++) {
    int u, v, w;
    scanf("%d%d%d", &u, &v, &w);
    u--, v--;
    nbrs[u].push_back(pii(v, w));
    nbrs[v].push_back(pii(u, w));
  }

  ps[0] = -1;
  qi q;
  q.push(0);

  while (! q.empty()) {
    int u = q.front(); q.pop();
    int &up = ps[u];
    vpii &nbru = nbrs[u];

    for (vpii::iterator vit = nbru.begin(); vit != nbru.end(); vit++) {
      int &v = vit->first;
      if (v != up) {
	cns[u]++;
	ps[v] = u;
	pws[v] = vit->second;
	q.push(v);
      }
    }
  }

  for (int u = 0; u < n; u++)
    if (cns[u] == 0) q.push(u);

  ll sum = 0;
  while (! q.empty()) {
    int u = q.front(); q.pop();
    int &up = ps[u];

    ss[u]++;
    sum += (ll)pws[u] * ss[u] * (n - ss[u]);

    if (up >= 0) {
      ss[up] += ss[u];
      if (--cns[up] == 0) q.push(up);
    }
  }

  printf("%lld\n", sum * 2);
  return 0;
}
0