結果

問題 No.778 クリスマスツリー
ユーザー kyunakyuna
提出日時 2019-07-27 21:53:49
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,693 bytes
コンパイル時間 837 ms
コンパイル使用メモリ 77,896 KB
実行使用メモリ 23,888 KB
最終ジャッジ日時 2023-09-15 11:11:57
合計ジャッジ時間 2,914 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,376 KB
testcase_06 AC 97 ms
23,568 KB
testcase_07 AC 57 ms
17,980 KB
testcase_08 WA -
testcase_09 AC 136 ms
17,256 KB
testcase_10 AC 135 ms
17,236 KB
testcase_11 AC 136 ms
17,340 KB
testcase_12 AC 122 ms
17,176 KB
testcase_13 AC 89 ms
16,968 KB
testcase_14 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

template<typename Abel> struct BIT {
    const Abel UNITY_SUM = 0;
    vector<Abel> dat;
    BIT(int n) : dat(n, UNITY_SUM) { }  // [0, n)
    inline void add(int i, Abel x) {
        while (i < dat.size()) { dat[i] += x; i |= i + 1; }
    }
    inline Abel sum(int i) {    // [0, i]
        Abel res = UNITY_SUM;
        while (i >= 0) { res += dat[i]; i = (i & (i + 1)) - 1; }
        return res;
    }
    inline Abel sum(int a, int b) { return sum(b - 1) - sum(a - 1); }   // [a, b)
    /* debug */
    Abel operator[](int i) { return sum(i, i + 1); }
    void dump() {
        for (int i = 0; i < dat.size(); ++i) cout << sum(i, i + 1) << ",";
        cout << endl;
    }
};

struct EulerTourOnVertex {
    vector<int> posL, posR;
    vector<vector<int>> g;
    int pos;
    EulerTourOnVertex(int n) : posL(n), posR(n), g(n) { }
    void add_edge(int u, int v) {
        g[u].emplace_back(v);
        g[v].emplace_back(u);
    }
    void dfs(int u, int p) {
        posL[u] = pos++;
        for (int v: g[u]) if (v != p) {
            dfs(v, u);
            pos++;
        }
        posR[u] = pos;
    }
    void build(int r = 0) {
        pos = 0;
        dfs(r, -1);
    }
};

int main() {
    int n; cin >> n;
    EulerTourOnVertex et(n);
    for (int u = 1; u < n; u++) {
        int p; cin >> p;
        et.add_edge(p, u);
    }
    et.build();
    BIT<int> bit(n * 2);
    int cnt = 0;
    for (int i = n - 1; i >= 0; i--) {
        int left = et.posL[i];
        int right = et.posR[i];
        cnt += bit.sum(left, right + 1);
        bit.add(left, 1);
    }
    cout << cnt << endl;
    return 0;
}
0