結果

問題 No.1103 Directed Length Sum
ユーザー kacho65535kacho65535
提出日時 2020-12-23 22:29:44
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 1,075 ms / 3,000 ms
コード長 1,635 bytes
コンパイル時間 1,606 ms
コンパイル使用メモリ 176,296 KB
実行使用メモリ 190,736 KB
最終ジャッジ日時 2023-10-21 15:20:51
合計ジャッジ時間 13,625 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 751 ms
190,736 KB
testcase_03 AC 452 ms
97,492 KB
testcase_04 AC 555 ms
58,532 KB
testcase_05 AC 1,075 ms
98,508 KB
testcase_06 AC 331 ms
39,088 KB
testcase_07 AC 62 ms
12,040 KB
testcase_08 AC 96 ms
16,528 KB
testcase_09 AC 38 ms
8,872 KB
testcase_10 AC 147 ms
21,524 KB
testcase_11 AC 627 ms
63,292 KB
testcase_12 AC 319 ms
39,616 KB
testcase_13 AC 148 ms
22,052 KB
testcase_14 AC 29 ms
7,552 KB
testcase_15 AC 238 ms
31,636 KB
testcase_16 AC 745 ms
70,928 KB
testcase_17 AC 758 ms
73,580 KB
testcase_18 AC 147 ms
21,444 KB
testcase_19 AC 635 ms
65,012 KB
testcase_20 AC 46 ms
9,928 KB
testcase_21 AC 87 ms
15,208 KB
testcase_22 AC 497 ms
53,532 KB
testcase_23 AC 271 ms
33,416 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define mod 1000000007ll
#define loop(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
#define putout(a) cout << a << '\n'
#define Sum(v) accumulate(all(v), 0ll)
void bfs(vector<vector<ll>> &G, vector<ll> &dist, ll s)
{
    queue<ll> que;
    dist[s] = 0;
    que.push(s);
    while (!que.empty())
    {
        ll v = que.front();
        que.pop();
        for (auto next_v : G[v])
        {
            if (dist[next_v] != -1)
                continue;
            dist[next_v] = dist[v] + 1;
            que.push(next_v);
        }
    }
}
vector<ll> sz;
void dfs(vector<vector<ll>> &G, ll v, ll p)
{
    for (auto nv : G[v])
    {
        if (nv == p)
            continue;
        dfs(G, nv, v);
    }
    sz[v] = 1;
    for (auto nv : G[v])
    {
        if (nv == p)
            continue;
        sz[v] += sz[nv];
    }
}
int main()
{
    ll N;
    cin >> N;
    vector<vector<ll>> G(N);
    ll root = 0; //bとして1度も出現しないのが根
    sz.resize(N);
    vector<ll> A(N - 1), B(N - 1), x(N - 1), y(N - 1), used(N, false);
    loop(i, N - 1)
    {
        cin >> A[i] >> B[i];
        A[i]--;
        B[i]--;
        used[B[i]] = true;
        G[A[i]].emplace_back(B[i]);
    }
    loop(i, N) if (!used[i]) root = i;
    vector<ll> dist(N, -1);
    bfs(G, dist, root);
    dfs(G, root, -1);
    loop(i, N - 1) x[i] = dist[B[i]]; //dist[A[i]]+1でもよい
    loop(i, N - 1) y[i] = sz[B[i]];
    ll ans = 0;
    loop(i, N - 1)
    {
        ans += x[i] * y[i] % mod;
        ans %= mod;
    }
    putout(ans);
    return 0;
}
0