結果

問題 No.271 next_permutation (2)
ユーザー lam6er
提出日時 2025-03-31 17:53:10
言語 PyPy3
(7.3.15)
結果
MLE  
実行時間 -
コード長 2,007 bytes
コンパイル時間 217 ms
コンパイル使用メモリ 82,604 KB
実行使用メモリ 578,436 KB
最終ジャッジ日時 2025-03-31 17:54:24
合計ジャッジ時間 6,674 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other MLE * 1 -- * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
MOD = 10**9 + 7

def next_permutation(arr):
    n = len(arr)
    k = n - 2
    while k >= 0 and arr[k] >= arr[k+1]:
        k -= 1
    if k == -1:
        return False
    l = n - 1
    while arr[l] <= arr[k]:
        l -= 1
    arr[k], arr[l] = arr[l], arr[k]
    arr[k+1:] = reversed(arr[k+1:])
    return True

def inversion_number(arr):
    max_val = max(arr) if arr else 0
    ft = [0]*(max_val + 2)
    res = 0
    for i in reversed(range(len(arr))):
        x = arr[i]
        while x > 0:
            res += ft[x]
            x -= x & -x
        x = arr[i] + 1
        while x <= max_val + 1:
            ft[x] += 1
            x += x & -x
        res %= MOD
    return res % MOD

def main():
    N, K = map(int, sys.stdin.readline().split())
    p = list(map(int, sys.stdin.readline().split()))
    if K == 0:
        print(0)
        return
    if N == 1:
        print(0)
        return
    seen = {}
    sequence = []
    current = p.copy()
    sum_inv = 0
    cycle_found = False
    total = 0
    steps = 0
    for _ in range(K):
        key = tuple(current)
        if key in seen:
            idx = seen[key]
            cycle_len = len(sequence) - idx
            cycle_sum = (total - sum(sequence[:idx])) % MOD
            remaining = K - idx
            cycles = remaining // cycle_len
            total_cycle = (cycles * cycle_sum) % MOD
            rem_steps = remaining % cycle_len
            rem_sum = sum(sequence[idx:idx+rem_steps]) % MOD
            total = (sum(sequence[:idx]) + total_cycle + rem_sum) % MOD
            cycle_found = True
            break
        seen[key] = len(sequence)
        inv = inversion_number(current)
        sequence.append(inv)
        total = (total + inv) % MOD
        steps += 1
        if not next_permutation(current):
            current = list(range(1, N+1))
        if steps >= K:
            break
    if not cycle_found:
        print(total % MOD)
        return
    print(total % MOD)

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