結果

問題 No.778 クリスマスツリー
ユーザー t98slidert98slider
提出日時 2023-07-12 23:50:12
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 75 ms / 2,000 ms
コード長 1,181 bytes
コンパイル時間 1,580 ms
コンパイル使用メモリ 169,380 KB
実行使用メモリ 30,404 KB
最終ジャッジ日時 2023-10-12 13:36:26
合計ジャッジ時間 4,046 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,352 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 2 ms
4,352 KB
testcase_03 AC 1 ms
4,348 KB
testcase_04 AC 2 ms
4,352 KB
testcase_05 AC 2 ms
4,348 KB
testcase_06 AC 55 ms
30,404 KB
testcase_07 AC 23 ms
9,612 KB
testcase_08 AC 75 ms
19,348 KB
testcase_09 AC 65 ms
11,640 KB
testcase_10 AC 65 ms
11,736 KB
testcase_11 AC 63 ms
11,636 KB
testcase_12 AC 62 ms
11,744 KB
testcase_13 AC 40 ms
11,736 KB
testcase_14 AC 54 ms
30,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

template <class T> struct fenwick_tree {
    using U = T;

    public:
    fenwick_tree() : _n(0) {}
    fenwick_tree(int n) : _n(n), data(n) {}

    void add(int p, T x) {
        assert(0 <= p && p < _n);
        p++;
        while (p <= _n) {
            data[p - 1] += U(x);
            p += p & -p;
        }
    }

    T sum(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        return sum(r) - sum(l);
    }

    private:
    int _n;
    std::vector<U> data;

    U sum(int r) {
        U s = 0;
        while (r > 0) {
            s += data[r - 1];
            r -= r & -r;
        }
        return s;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int N;
    cin >> N;
    vector<vector<int>> G(N);
    fenwick_tree<int> fw(N);
    for(int i = 1; i < N; i++){
        int p;
        cin >> p;
        G[p].emplace_back(i);
    }
    ll ans = 0;
    auto dfs = [&](auto self, int v) -> void {
        ans += fw.sum(0, v);
        fw.add(v, 1);
        for(auto &&u : G[v]) self(self, u);
        fw.add(v, -1);
    };
    dfs(dfs, 0);
    cout << ans << '\n';
}
0