結果

問題 No.2382 Amidakuji M
ユーザー SPD_9X2
提出日時 2023-07-14 21:36:29
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 172 ms / 2,000 ms
コード長 715 bytes
コンパイル時間 346 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 107,520 KB
最終ジャッジ日時 2024-09-16 06:28:15
合計ジャッジ時間 3,220 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

def bitadd(a,w,bit): #aにwを加える(1-origin)
 
    x = a
    while x <= (len(bit)-1):
        bit[x] += w
        x += x & (-1 * x)
 
def bitsum(a,bit): #ind 1~aまでの和を求める
 
    ret = 0
    x = a
    while x > 0:
        ret += bit[x]
        x -= x & (-1 * x)
    return ret


N,M = map(int,input().split())

BIT = [0] * (N+1)
a = list(map(int,input().split()))

ans = 0
for i in range(N):

    ans += i - bitsum(a[i],BIT)
    bitadd(a[i],1,BIT)

if ans % M == 0:
    print (ans)
elif M % 2 == 0 and ans % 2 == 1:
    print (-1)
else:
    
    now = ans // M * M
    while (True):

        if now >= ans and (now-ans) % 2 == 0:
            print (now)
            break

        now += M
    
0