結果

問題 No.778 クリスマスツリー
ユーザー kyunakyuna
提出日時 2019-07-27 21:54:12
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 138 ms / 2,000 ms
コード長 1,699 bytes
コンパイル時間 655 ms
コンパイル使用メモリ 78,292 KB
実行使用メモリ 23,888 KB
最終ジャッジ日時 2024-04-22 03:09:03
合計ジャッジ時間 2,338 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 1 ms
6,940 KB
testcase_02 AC 1 ms
6,944 KB
testcase_03 AC 2 ms
6,944 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,944 KB
testcase_06 AC 95 ms
23,888 KB
testcase_07 AC 53 ms
18,112 KB
testcase_08 AC 138 ms
20,480 KB
testcase_09 AC 133 ms
17,332 KB
testcase_10 AC 135 ms
17,484 KB
testcase_11 AC 130 ms
17,572 KB
testcase_12 AC 127 ms
17,460 KB
testcase_13 AC 91 ms
17,204 KB
testcase_14 AC 98 ms
23,888 KB
権限があれば一括ダウンロードができます

ソースコード

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);
    long long 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