結果

問題 No.121 傾向と対策:門松列(その2)
ユーザー 👑 colognecologne
提出日時 2022-02-09 09:12:40
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 4,694 ms / 5,000 ms
コード長 1,607 bytes
コンパイル時間 772 ms
コンパイル使用メモリ 87,184 KB
実行使用メモリ 301,652 KB
最終ジャッジ日時 2023-09-06 12:58:52
合計ジャッジ時間 13,459 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 211 ms
91,356 KB
testcase_01 AC 293 ms
98,412 KB
testcase_02 AC 122 ms
79,424 KB
testcase_03 AC 1,146 ms
267,144 KB
testcase_04 AC 4,694 ms
301,652 KB
testcase_05 AC 1,091 ms
267,068 KB
testcase_06 AC 1,124 ms
267,756 KB
testcase_07 AC 1,270 ms
256,852 KB
testcase_08 AC 1,298 ms
268,024 KB
権限があれば一括ダウンロードができます

ソースコード

diff #


class FenwickTree:
    """
    Implements fenwick tree
    """

    def __init__(self, N: int):
        """
        Initializes fenwick tree with size N, indexed from 0 to N-1.
        """
        self.__N = N
        self.__data = [0] * N

    def add(self, pos: int, val: int):
        """
        Applies A[pos] += val
        """
        assert 0 <= pos < self.__N
        pos += 1
        while pos <= self.__N:
            self.__data[pos - 1] += val
            pos += pos & -pos

    def sum(self, s: int, e: int):
        """
        Calculates sum(A[s:e]), where 0 <= s <= e <= N.
        """
        assert 0 <= s <= e <= self.__N
        return self.__sum(e) - self.__sum(s)

    def __sum(self, pos: int):
        ans = 0
        while pos > 0:
            ans += self.__data[pos - 1]
            pos -= pos & -pos
        return ans


def main():
    N = int(input())
    *A, = map(int, input().split())

    D = {}
    for i in range(N):
        if A[i] not in D:
            D[A[i]] = []
        D[A[i]].append(i)

    ans = 0

    F = FenwickTree(N)
    for k in sorted(D.keys()):
        for i in D[k]:
            ans += F.sum(0, i) * F.sum(i+1, N)
        for i in D[k]:
            F.add(i, 1)

    F = FenwickTree(N)
    for k in sorted(D.keys(), reverse=True):
        for i in D[k]:
            ans += F.sum(0, i) * F.sum(i+1, N)
        for i in D[k]:
            F.add(i, 1)

    for k in D.keys():
        v = D[k]
        for i in range(len(v)):
            ans += (len(v)-1-2*i) * v[i]
            ans += i * (len(v)-i)

    print(ans)


if __name__ == '__main__':
    main()
0