結果

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

ソースコード

diff #

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 2)  # 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

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 20! and handle overflow
    fact = [1]  # fact[0] = 0! = 1
    for i in range(1, 21):
        fact.append(fact[i-1] * i)
    for i in range(len(fact)):
        if fact[i] > 1e18:
            fact[i] = float('inf')
    
    ft = FenwickTree(n)
    for i in range(1, n+1):
        ft.update(i, 1)
    
    ans = 0
    inf_flag = False
    
    for i in range(n):
        current_num = p[i]
        k = ft.query(current_num - 1)
        m = n - i - 1  # remaining positions
        
        if m <= 20:
            current_fact = fact[m]
        else:
            current_fact = float('inf')
        
        contrib = k * current_fact
        
        if not inf_flag:
            if current_fact == float('inf'):
                if k > 0:
                    ans = float('inf')
                    inf_flag = True
            else:
                ans += contrib
                if ans > 1e18:
                    ans = float('inf')
                    inf_flag = True
        
        ft.update(current_num, -1)
    
    if ans == float('inf'):
        print(ans)
    else:
        print(ans + 1)

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