結果

問題 No.121 傾向と対策:門松列(その2)
ユーザー nebukuro09nebukuro09
提出日時 2017-03-25 11:32:21
言語 D
(dmd 2.106.1)
結果
TLE  
実行時間 -
コード長 2,323 bytes
コンパイル時間 705 ms
コンパイル使用メモリ 114,892 KB
実行使用メモリ 44,636 KB
最終ジャッジ日時 2023-09-03 12:39:13
合計ジャッジ時間 12,517 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 210 ms
11,484 KB
testcase_01 AC 324 ms
12,336 KB
testcase_02 AC 21 ms
4,380 KB
testcase_03 AC 2,978 ms
44,636 KB
testcase_04 TLE -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
権限があれば一括ダウンロードができます

ソースコード

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.stdio;


void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = A.dup.sort().uniq.array;

    int[int] compressor;
    foreach (i, e; enumerate(B)) {
        compressor[e] = i.to!int;
    }
    foreach (i; 0..N) {
        A[i] = compressor[A[i]];
    }
    auto M = B.length.to!int - 1;

    auto st_left = new SegmentTree(M+1);
    auto st_right = new SegmentTree(M+1);
    auto st_same = new SegmentTree(M+1);

    foreach (i; 1..N) {
        st_right.add(A[i], 1);
    }

    long ans = 0;
    foreach (i; 1..N-1) {
        st_right.add(A[i], -1);
        st_left.add(A[i-1], 1);
        auto same = st_same.sum(A[i-1], A[i-1]);
        st_same.add(A[i-1], -same);
        st_same.add(A[i-1], st_left.sum(A[i-1], A[i-1]) * st_right.sum(A[i-1], A[i-1]));
        
        if (A[i] > 0) {
            ans += st_left.sum(0, A[i]-1) * st_right.sum(0, A[i]-1) - st_same.sum(0, A[i]-1);
        }
        if (A[i] < M) {
            ans += st_left.sum(A[i]+1, M) * st_right.sum(A[i]+1, M) - st_same.sum(A[i]+1, M);
        }
    }
    
    ans.writeln;
}

class SegmentTree {
    long[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new long[](size);
        fill(table, 0);
    }

    void add(int pos, long num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, long num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    long sum(int pl, int pr) {
        return sum(pl, pr, 0, 0, size/2-1);
    }

    long sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}
0