結果

問題 No.1103 Directed Length Sum
ユーザー simansiman
提出日時 2021-10-12 03:01:38
言語 C++17(clang)
(17.0.6 + boost 1.83.0)
結果
AC  
実行時間 968 ms / 3,000 ms
コード長 1,217 bytes
コンパイル時間 2,112 ms
コンパイル使用メモリ 108,028 KB
実行使用メモリ 62,000 KB
最終ジャッジ日時 2023-10-14 16:03:07
合計ジャッジ時間 10,851 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 12 ms
30,816 KB
testcase_01 AC 12 ms
30,772 KB
testcase_02 AC 681 ms
62,000 KB
testcase_03 AC 489 ms
50,772 KB
testcase_04 AC 533 ms
40,964 KB
testcase_05 AC 968 ms
48,456 KB
testcase_06 AC 340 ms
37,584 KB
testcase_07 AC 78 ms
32,460 KB
testcase_08 AC 118 ms
33,252 KB
testcase_09 AC 50 ms
31,764 KB
testcase_10 AC 163 ms
34,168 KB
testcase_11 AC 591 ms
41,836 KB
testcase_12 AC 342 ms
37,540 KB
testcase_13 AC 167 ms
34,296 KB
testcase_14 AC 39 ms
31,536 KB
testcase_15 AC 263 ms
36,056 KB
testcase_16 AC 668 ms
43,320 KB
testcase_17 AC 698 ms
43,816 KB
testcase_18 AC 162 ms
34,248 KB
testcase_19 AC 601 ms
42,160 KB
testcase_20 AC 59 ms
32,080 KB
testcase_21 AC 107 ms
33,032 KB
testcase_22 AC 484 ms
40,072 KB
testcase_23 AC 283 ms
36,340 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cassert>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <map>
#include <queue>
#include <set>
#include <string.h>
#include <vector>

using namespace std;
typedef long long ll;
typedef pair<int, ll> Node;

const ll MOD = 1000000007;
const int MAX_N = 1000010;
vector<int> E[MAX_N];
int P[MAX_N];
int N;

int find_root(int v) {
  if (P[v] == -1) return v;
  return find_root(P[v]);
}

ll dfs(int v, int depth) {
  ll len = 0;

  for (int u : E[v]) {
    len += depth * (depth + 1) / 2;
    len %= MOD;
    len += dfs(u, depth + 1);
    len %= MOD;
  }

  return len;
}

int main() {
  memset(P, -1, sizeof(P));
  cin >> N;

  for (int i = 0; i < N - 1; ++i) {
    int a, b;
    cin >> a >> b;

    E[a].push_back(b);
    P[b] = a;
  }

  int root = find_root(1);
  ll ans = 0;
  // cout << dfs(root, 1) << endl;
  queue<Node> que;
  que.push(Node(root, 1));

  while (not que.empty()) {
    Node node = que.front();
    int v = node.first;
    ll depth = node.second;
    que.pop();

    for (int u : E[v]) {
      ans += depth * (depth + 1) / 2;
      ans %= MOD;
      que.push(Node(u, depth + 1));
    }
  }

  cout << ans << endl;

  return 0;
}
0