結果

問題 No.1597 Matrix Sort
ユーザー gew1fw
提出日時 2025-06-12 21:37:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 438 ms / 1,500 ms
コード長 1,460 bytes
コンパイル時間 228 ms
コンパイル使用メモリ 82,296 KB
実行使用メモリ 248,992 KB
最終ジャッジ日時 2025-06-12 21:39:59
合計ジャッジ時間 7,722 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

def main():
    input = sys.stdin.read().split()
    idx = 0
    N = int(input[idx]); idx +=1
    K = int(input[idx]); idx +=1
    P = int(input[idx]); idx +=1

    A = list(map(int, input[idx:idx+N]))
    idx += N
    B = list(map(int, input[idx:idx+N]))
    idx += N

    # Preprocess B
    cnt_B = [0] * P
    for b in B:
        cnt_B[b] += 1

    # Compute prefix sums
    prefix_B = [0] * P
    prefix_B[0] = cnt_B[0]
    for i in range(1, P):
        prefix_B[i] = prefix_B[i-1] + cnt_B[i]

    # Binary search
    low = 0
    high = P - 1
    answer = high

    while low <= high:
        mid = (low + high) // 2
        total = 0

        for a in A:
            L = (-a) % P
            R = (mid - a) % P

            if L <= R:
                if L == 0:
                    current = prefix_B[R]
                else:
                    current = prefix_B[R] - prefix_B[L-1]
                total += current
            else:
                # L > R, count from L to P-1 and from 0 to R
                part1 = prefix_B[P-1]
                if L > 0:
                    part1 -= prefix_B[L-1]
                part2 = prefix_B[R]
                total += part1 + part2

            # Early exit if total exceeds K
            if total > K:
                break

        if total >= K:
            answer = mid
            high = mid - 1
        else:
            low = mid + 1

    print(answer)

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