結果

問題 No.1103 Directed Length Sum
ユーザー merom686
提出日時 2020-07-03 21:44:34
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 278 ms / 3,000 ms
コード長 1,291 bytes
コンパイル時間 1,061 ms
コンパイル使用メモリ 96,180 KB
最終ジャッジ日時 2025-01-11 14:23:49
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

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