結果

問題 No.778 クリスマスツリー
ユーザー nanaenanae
提出日時 2018-12-29 12:52:49
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 157 ms / 2,000 ms
コード長 2,019 bytes
コンパイル時間 708 ms
コンパイル使用メモリ 98,920 KB
実行使用メモリ 44,932 KB
最終ジャッジ日時 2023-09-03 21:46:36
合計ジャッジ時間 2,901 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 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,376 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 119 ms
44,932 KB
testcase_07 AC 64 ms
14,160 KB
testcase_08 AC 157 ms
32,400 KB
testcase_09 AC 147 ms
24,144 KB
testcase_10 AC 133 ms
24,896 KB
testcase_11 AC 132 ms
24,160 KB
testcase_12 AC 128 ms
24,888 KB
testcase_13 AC 91 ms
24,480 KB
testcase_14 AC 118 ms
44,760 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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



void main() {
    int n;
    scan(n);
    auto a = readln.split.to!(int[]);
    long ans = solve(n, a);
    ans.writeln;
}

long solve(int n, int[] a) {
    auto ch = new int[][](n, 0);

    foreach (i, ai; a) {
        ch[ai] ~= i.to!int + 1;
    }

    int[] et;
    auto begin = new int[](n);
    auto end = new int[](n);

    void dfs(int v) {
        begin[v] = et.length.to!int;
        et ~= v;

        foreach (u ; ch[v]) {
            dfs(u);
            et ~= v;
        }

        end[v] = et.length.to!int;
    }

    dfs(0);

    debug {
        stderr.writeln(et);
        stderr.writeln(begin);
        stderr.writeln(end);
    }

    auto bit = FenwickTree!(int)(2*n);

    long ans;

    foreach_reverse (i ; 0 .. n) {
        int cnt = bit.sum(end[i]) - bit.sum(begin[i]);
        ans += cnt;
        bit.add(begin[i], 1);
    }

    return ans;
}

struct FenwickTree(T) {
    private {
        int _size;
        T[] _data;
    }

    this(int N) {
        _size = N;
        _data = new T[](_size + 1);
    }

    void add(int i, T x) {
        i++;
        while (i <= _size) {
            _data[i] += x;
            i += i & (-i);
        }
    }

    T sum(int r) {
        T res = 0;
        while (r > 0) {
            res += _data[r];
            r -= r & (-r);
        }
        return res;
    }
}



void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}


void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}
0