結果

問題 No.2759 Take Pictures, Elements?
ユーザー NP
提出日時 2024-05-17 21:58:58
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,172 bytes
コンパイル時間 230 ms
コンパイル使用メモリ 82,828 KB
実行使用メモリ 65,520 KB
最終ジャッジ日時 2025-06-20 13:17:43
合計ジャッジ時間 2,020 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 11 WA * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys
import bisect
input = sys.stdin.read

def main():
    data = input().split()
    N = int(data[0])
    Q = int(data[1])
    A = list(map(int, data[2:N+2]))
    B = list(map(int, data[N+2:]))
    value_to_indices = defaultdict(list)
    for index, value in enumerate(A, start=1):
        value_to_indices[value].append(index)
    
    current_position = 1
    total_cost = 0
    
    def find_nearest_index(indices, current_position):
        pos = bisect.bisect_left(indices, current_position)
        if pos == 0:
            return indices[0]
        if pos == len(indices):
            return indices[-1]
        before = indices[pos - 1]
        after = indices[pos]
        if abs(before - current_position) <= abs(after - current_position):
            return before
        else:
            return after
    
    for target in B:
        possible_indices = value_to_indices[target]
        best_index = find_nearest_index(possible_indices, current_position)
        total_cost += abs(current_position - best_index)
        current_position = best_index
    
    print(total_cost)

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