結果

問題 No.2382 Amidakuji M
ユーザー titiatitia
提出日時 2023-07-14 22:10:06
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 732 ms / 2,000 ms
コード長 1,412 bytes
コンパイル時間 869 ms
コンパイル使用メモリ 10,840 KB
実行使用メモリ 30,152 KB
最終ジャッジ日時 2023-10-14 12:23:14
合計ジャッジ時間 7,338 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 15 ms
8,328 KB
testcase_01 AC 16 ms
8,304 KB
testcase_02 AC 14 ms
8,044 KB
testcase_03 AC 283 ms
17,584 KB
testcase_04 AC 550 ms
25,600 KB
testcase_05 AC 84 ms
10,876 KB
testcase_06 AC 309 ms
19,112 KB
testcase_07 AC 194 ms
14,908 KB
testcase_08 AC 27 ms
8,808 KB
testcase_09 AC 459 ms
23,160 KB
testcase_10 AC 689 ms
29,512 KB
testcase_11 AC 238 ms
15,712 KB
testcase_12 AC 442 ms
23,352 KB
testcase_13 AC 15 ms
8,396 KB
testcase_14 AC 14 ms
7,988 KB
testcase_15 AC 14 ms
8,224 KB
testcase_16 AC 15 ms
8,388 KB
testcase_17 AC 14 ms
8,316 KB
testcase_18 AC 15 ms
8,320 KB
testcase_19 AC 732 ms
30,080 KB
testcase_20 AC 726 ms
30,072 KB
testcase_21 AC 719 ms
30,152 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from math import gcd

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

LEN=len(A)
MAX=max(A)
MIN=min(A)

BIT=[0]*(MAX-MIN+2) # 出現回数をbit indexed treeの形でもっておく.

def update(v,w): # index vにwを加える
    while v<=MAX-MIN+1:
        BIT[v]+=w
        v+=(v&(-v)) # 自分を含む大きなノードへ. たとえばv=3→v=4

def getvalue(v): # MIN~vの区間の和を求める
    ANS=0
    while v!=0:
        ANS+=BIT[v]
        v-=(v&(-v)) # たとえばv=3→v=2へ
    return ANS

ANS=0        
for i in range(LEN): # A[0],A[1],...とBITを更新しながら,各A[i]について転倒数を求める.
    bit_ai=A[i]-MIN+1 # A[i]がBITの中で何番目か

    ANS+=i # 今まで出現した個数.
    ANS-=getvalue(bit_ai) # 今まで出現した中で,MIN~bit_aiの個数を減らす.
    # bit_ai~MAXの出現個数が転倒数

    update(bit_ai,1)

if ANS==0:
    print(0)

elif ANS%2==0 and M%2==0:
    if ANS<=M:
        print(M)
    else:
        x=(ANS+M-1)//M
        print(x*M)
        
elif ANS%2==1 and M%2==0:
    print(-1)

elif ANS%2==0 and M%2==1:
    M*=2

    if ANS<=M:
        print(M)
    else:
        x=(ANS+M-1)//M
        print(x*M)
        
elif ANS%2==1 and M%2==1:
    if ANS<=M:
        print(M)
    else:
        x=(ANS+M-1)//M
        now=x*M

        while now%2!=ANS%2:
            now+=M

        print(now)
        
    
0