結果

問題 No.1115 二つの数列 / Two Sequences
ユーザー AEn
提出日時 2022-05-20 00:02:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 147 ms / 2,000 ms
コード長 1,297 bytes
コンパイル時間 132 ms
コンパイル使用メモリ 82,300 KB
実行使用メモリ 109,696 KB
最終ジャッジ日時 2024-09-19 04:50:04
合計ジャッジ時間 5,706 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

# dataの長さは1番目からnを2進数にしたときのLSBに相当
class Binary_Indexed_Tree:
    def __init__(self, n) -> None:
        self._n = n
        self.data = [0] * (n+1)
        self.depth = n.bit_length()
    
    # al〜arに一律加算ならいもす法でlにx加算、r+1に-x加算すれば良い
    # aiの値の取得はiまでのsum

    # 任意の要素ai←ai+xを行う O(logn)
    def add(self, p, x) -> None:
        # pのindexが0以上n-1以下を保証
        assert 0 <= p < self._n
        # 1-indexedに変換
        p += 1
        while p <= self._n:
            # 加算
            self.data[p-1] += x
            # LSBの加算
            p += p & (-p)
    
    # 区間[l, r)
    def sum(self, l, r) -> int:
        assert 0 <= l <= r <= self._n
        return self._sum(r) - self._sum(l)
    
    def _sum(self, d) -> int:
        sm = 0
        while d > 0:
            sm += self.data[d-1]
            # LSB減算
            d -= d & (-d)
        return sm

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
d = {}
for i in range(N):
    d[B[i]] = i
for i in range(N):
    A[i] = d[A[i]]
BIT = Binary_Indexed_Tree(N)
res = 0
for i in range(N):
    BIT.add(A[i], 1)
    res += BIT.sum(A[i]+1, N)
print(res)
0