結果

問題 No.696 square1001 and Permutation 5
ユーザー lam6er
提出日時 2025-04-16 00:09:47
言語 PyPy3
(7.3.15)
結果
MLE  
実行時間 -
コード長 1,082 bytes
コンパイル時間 524 ms
コンパイル使用メモリ 81,840 KB
実行使用メモリ 848,236 KB
最終ジャッジ日時 2025-04-16 00:10:48
合計ジャッジ時間 4,178 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 2
other MLE * 1 -- * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

n = int(input())
p = list(map(int, input().split()))

# Precompute factorial up to (n-1)!
fact = [1] * n
for i in range(1, n):
    fact[i] = fact[i-1] * i

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 2)  # Using n+2 to avoid issues with 1-based indexing
    
    def update(self, idx, delta):
        while idx <= self.n:
            self.tree[idx] += delta
            idx += idx & -idx
    
    def query(self, idx):
        res = 0
        while idx > 0:
            res += self.tree[idx]
            idx -= idx & -idx
        return res

# Initialize Fenwick Tree with all elements present
ft = FenwickTree(n)
for num in range(1, n+1):
    ft.update(num, 1)

result = 0
for i in range(n):
    current = p[i]
    # Calculate the number of elements less than current that are still available
    count = ft.query(current - 1)
    remaining = n - 1 - i
    if remaining >= 0:
        result += count * fact[remaining]
    # Remove the current element from the Fenwick Tree
    ft.update(current, -1)

print(result + 1)
0