結果

問題 No.696 square1001 and Permutation 5
ユーザー gew1fw
提出日時 2025-06-12 19:14:38
言語 PyPy3
(7.3.15)
結果
MLE  
実行時間 -
コード長 1,028 bytes
コンパイル時間 374 ms
コンパイル使用メモリ 82,464 KB
実行使用メモリ 848,512 KB
最終ジャッジ日時 2025-06-12 19:15:00
合計ジャッジ時間 3,828 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 2
other MLE * 1 -- * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 2)  # 1-based indexing

    def update_point(self, idx, delta):
        while idx <= self.n:
            self.tree[idx] += delta
            idx += idx & -idx

    def query_prefix(self, idx):
        res = 0
        while idx > 0:
            res += self.tree[idx]
            idx -= idx & -idx
        return res

def main():
    import sys
    input = sys.stdin.read().split()
    n = int(input[0])
    p = list(map(int, input[1:n+1]))
    
    # Precompute factorials up to (n-1)!
    fact = [1] * n
    for i in range(1, n):
        fact[i] = fact[i-1] * i
    
    ft = FenwickTree(n)
    for i in range(1, n+1):
        ft.update_point(i, 1)
    
    ans = 0
    for i in range(n):
        current = p[i]
        count = ft.query_prefix(current - 1)
        if i < n - 1:
            ans += count * fact[n - 1 - i]
        ft.update_point(current, -1)
    
    print(ans + 1)

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