結果

問題 No.778 クリスマスツリー
ユーザー nebukuro09nebukuro09
提出日時 2018-12-25 04:01:08
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 248 ms / 2,000 ms
コード長 1,726 bytes
コンパイル時間 681 ms
コンパイル使用メモリ 103,688 KB
実行使用メモリ 40,288 KB
最終ジャッジ日時 2023-09-03 21:45:00
合計ジャッジ時間 3,924 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 149 ms
40,288 KB
testcase_07 AC 99 ms
17,024 KB
testcase_08 AC 248 ms
30,580 KB
testcase_09 AC 228 ms
26,196 KB
testcase_10 AC 228 ms
23,764 KB
testcase_11 AC 229 ms
23,716 KB
testcase_12 AC 221 ms
23,684 KB
testcase_13 AC 134 ms
22,852 KB
testcase_14 AC 154 ms
39,248 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto P = readln.split.map!(to!int).array;
    auto G = new int[][](N);
    foreach (i; 1..N) {
        G[P[i-1]] ~= i;
    }

    auto st = new SegmentTree!(long, (a,b)=>a+b, 0L)(N);
    long ans = 0;

    void dfs(int n) {
        ans += st.query(0, n);
        st.add(n, 1);
        foreach (m; G[n]) {
            dfs(m);
        }
        st.add(n, -1);
    }

    dfs(0);
    ans.writeln;
}


class SegmentTree(T, alias op, T e) {
    T[] table;
    int size;
    int offset;

    this(int n) {
        size = 1;
        while (size <= n) size <<= 1;
        size <<= 1;
        table = new T[](size);
        fill(table, e);
        offset = size / 2;
    }

    void assign(int pos, T val) {
        pos += offset;
        table[pos] = val;
        while (pos > 1) {
            pos /= 2;
            table[pos] = op(table[pos*2], table[pos*2+1]);
        }
    }

    void add(int pos, T val) {
        pos += offset;
        table[pos] += val;
        while (pos > 1) {
            pos /= 2;
            table[pos] = op(table[pos*2], table[pos*2+1]);
        }
    }

    T query(int l, int r) {
        if (r < l) return e;
        return query(l, r, 1, 0, offset-1);
    }

    T query(int l, int r, int i, int a, int b) {
        if (b < l || r < a) {
            return e;
        } else if (l <= a && b <= r) {
            return table[i];
        } else {
            return op(query(l, r, i*2, a, (a+b)/2), query(l, r, i*2+1, (a+b)/2+1, b));
        }
    }
}
0