結果

問題 No.1103 Directed Length Sum
ユーザー merom686merom686
提出日時 2020-07-03 21:44:34
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 335 ms / 3,000 ms
コード長 1,291 bytes
コンパイル時間 902 ms
コンパイル使用メモリ 93,660 KB
実行使用メモリ 49,732 KB
最終ジャッジ日時 2023-10-17 00:08:48
合計ジャッジ時間 5,264 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 218 ms
49,732 KB
testcase_03 AC 159 ms
23,860 KB
testcase_04 AC 162 ms
14,892 KB
testcase_05 AC 335 ms
23,332 KB
testcase_06 AC 104 ms
10,804 KB
testcase_07 AC 21 ms
5,064 KB
testcase_08 AC 34 ms
6,120 KB
testcase_09 AC 13 ms
4,348 KB
testcase_10 AC 48 ms
7,108 KB
testcase_11 AC 185 ms
15,880 KB
testcase_12 AC 106 ms
10,804 KB
testcase_13 AC 49 ms
7,140 KB
testcase_14 AC 11 ms
4,348 KB
testcase_15 AC 79 ms
9,152 KB
testcase_16 AC 217 ms
17,464 KB
testcase_17 AC 223 ms
17,924 KB
testcase_18 AC 47 ms
7,108 KB
testcase_19 AC 191 ms
16,144 KB
testcase_20 AC 16 ms
4,536 KB
testcase_21 AC 30 ms
5,940 KB
testcase_22 AC 155 ms
13,836 KB
testcase_23 AC 87 ms
9,680 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;

constexpr int P = 1000000007;

ll ans = 0;

struct Graph {
    struct Vertex { int n; };
    struct Edge { int i, n; };
    Graph(int n, int m) : v(n, { -1 }), e(m), n(n), m(0) {}
    void add_edge(int i, int j) {
        e[m] = { j, v[i].n };
        v[i].n = m;
        m++;
    }
    pair<ll, int> dfs(int i) {
        ll s = 0;
        int k = 0;
        for (int j = v[i].n; j >= 0; j = e[j].n) {
            Edge& o = e[j];
            auto p = dfs(o.i);
            s += p.first;
            k += p.second;
        }
        s += k;
        ans += s;
        return { s, k + 1 };
    }
    vector<Vertex> v;
    vector<Edge> e;
    int n, m;
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;

    Graph g(n, (n - 1) * 2);
    vector<char> x(n, 0);

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

        g.add_edge(a, b);
        x[b] = 1;
    }

    for (int i = 0; i < n; i++) {
        if (x[i] == 0) {
            g.dfs(i);
            cout << ans % P << endl;
            break;
        }
    }

    return 0;
}
0