結果

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

ソースコード

diff #

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

# Precompute the largest factorial: (n-1)!
current_fact = 1
for i in range(1, n):
    current_fact *= i

# Fenwick Tree implementation
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
ft = FenwickTree(n)
for i in range(1, n + 1):
    ft.update(i, 1)

ans = 0
for i in range(n):
    current = p[i]
    count = ft.query(current - 1)
    ans += count * current_fact

    # Update current_fact for the next step
    remaining = n - i - 1
    if remaining > 0:
        current_fact = current_fact // remaining
    else:
        current_fact = 1  # 0! is 1

    # Mark current as used
    ft.update(current, -1)

print(ans + 1)
0