結果

問題 No.778 クリスマスツリー
ユーザー PachicobuePachicobue
提出日時 2018-12-25 01:38:12
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 145 ms / 2,000 ms
コード長 2,070 bytes
コンパイル時間 2,390 ms
コンパイル使用メモリ 202,312 KB
実行使用メモリ 26,184 KB
最終ジャッジ日時 2024-04-22 03:03:18
合計ジャッジ時間 4,137 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 97 ms
26,080 KB
testcase_07 AC 47 ms
14,296 KB
testcase_08 AC 145 ms
19,784 KB
testcase_09 AC 131 ms
16,768 KB
testcase_10 AC 128 ms
16,768 KB
testcase_11 AC 126 ms
16,768 KB
testcase_12 AC 124 ms
16,620 KB
testcase_13 AC 86 ms
16,640 KB
testcase_14 AC 98 ms
26,184 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define show(x) std::cerr << #x << " = " << (x) << std::endl
using ll = long long;
using ull = unsigned long long;
struct Sum
{
    using T = ll;
    T operator()(const T& a, const T& b) const { return a + b; }
    static constexpr T id() { return 0; }
};
constexpr std::size_t PC(ull v) { return v = (v & 0x5555555555555555ULL) + (v >> 1 & 0x5555555555555555ULL), v = (v & 0x3333333333333333ULL) + (v >> 2 & 0x3333333333333333ULL), v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL, static_cast<std::size_t>(v * 0x0101010101010101ULL >> 56 & 0x7f); }
constexpr std::size_t LG(ull v) { return v == 0 ? 0 : (v--, v |= (v >> 1), v |= (v >> 2), v |= (v >> 4), v |= (v >> 8), v |= (v >> 16), v |= (v >> 32), PC(v)); }
constexpr ull SZ(const ull v) { return 1ULL << LG(v); }
class BinaryIndexedTree
{
public:
    using T = ll;
    BinaryIndexedTree(const std::size_t n) : data_num(n), size(SZ(n)), value(size + 1, 0) {}
    void add(const std::size_t a, const T& val)
    {
        for (std::size_t ind = a + 1; ind <= size; ind += ind & (-ind)) { value[ind] += val; }
    }
    T accumulate(const std::size_t a) const
    {
        T sum = 0;
        for (std::size_t ind = a + 1; ind != 0; ind &= ind - 1) { sum += value[ind]; }
        return sum;
    }
    T accumulate(const std::size_t l, const std::size_t r) const { return accumulate(r - 1) - (l == 0 ? 0 : accumulate(l - 1)); }

private:
    const std::size_t data_num, size;
    std::vector<T> value;
};

int main()
{
    int N;
    std::cin >> N;
    std::vector<std::vector<int>> g(N);
    for (int i = 1, A; i < N; i++) { std::cin >> A, g[A].push_back(i); }
    std::vector<int> l(N), r(N);
    int S = 0;
    auto dfs = [&](auto&& self, const int s) -> void {
        l[s] = S++;
        for (const int to : g[s]) { self(self, to); }
        r[s] = S++;
    };
    dfs(dfs, 0);
    BinaryIndexedTree bit(S);
    ll ans = 0;
    for (int i = N - 1; i >= 0; i--) {
        bit.add(l[i], 1);
        ans += bit.accumulate(l[i] + 1, r[i]);
    }
    std::cout << ans << std::endl;
    return 0;
}
0