結果

問題 No.121 傾向と対策:門松列(その2)
ユーザー maspymaspy
提出日時 2020-03-28 16:28:51
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 3,698 ms / 5,000 ms
コード長 2,130 bytes
コンパイル時間 616 ms
コンパイル使用メモリ 87,132 KB
実行使用メモリ 329,484 KB
最終ジャッジ日時 2023-08-30 17:57:16
合計ジャッジ時間 11,256 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 177 ms
97,004 KB
testcase_01 AC 250 ms
108,988 KB
testcase_02 AC 111 ms
78,448 KB
testcase_03 AC 838 ms
266,064 KB
testcase_04 AC 3,698 ms
329,484 KB
testcase_05 AC 838 ms
265,980 KB
testcase_06 AC 801 ms
265,772 KB
testcase_07 AC 844 ms
238,580 KB
testcase_08 AC 915 ms
243,560 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/ python3.8
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
A = tuple(map(int, readline().split()))


class BinaryIndexedTree():
    def __init__(self, seq):
        self.size = len(seq)
        self.depth = self.size.bit_length()
        self.build(seq)

    def build(self, seq):
        data = seq
        size = self.size
        for i, x in enumerate(data):
            j = i + (i & (-i))
            if j < size:
                data[j] += data[i]
        self.data = data

    def __repr__(self):
        return self.data.__repr__()

    def get_sum(self, i):
        data = self.data
        s = 0
        while i:
            s += data[i]
            i -= i & -i
        return s

    def add(self, i, x):
        data = self.data
        size = self.size
        while i < size:
            data[i] += x
            i += i & -i

    def find_kth_element(self, k):
        data = self.data
        size = self.size
        x, sx = 0, 0
        dx = 1 << (self.depth)
        for i in range(self.depth - 1, -1, -1):
            dx = (1 << i)
            if x + dx >= size:
                continue
            y = x + dx
            sy = sx + data[y]
            if sy < k:
                x, sx = y, sy
        return x + 1


def solve(A):
    x_to_i = {x: i for i, x in enumerate(sorted(set(A)))}
    num_to_ind = [[] for _ in range(len(x_to_i))]
    for i, x in enumerate(A, 1):
        num_to_ind[x_to_i[x]].append(i)
    ret = 0
    for t in range(2):
        bit = BinaryIndexedTree([0] * (N + 1))
        total_below = 0
        it = num_to_ind if t else reversed(num_to_ind)
        for ind in it:
            counts = [bit.get_sum(i) for i in ind]
            for x in counts:
                ret += x * (total_below - x)  # small, x, small
            n = len(ind)
            for i in range(1, n):
                ret -= (counts[i] - counts[i - 1]) * i * (n - i)  # x, small, x
            for i in ind:
                bit.add(i, 1)
            total_below += n
    return ret


answer = solve(A)
print(answer)
0