ABC030 C - 飛行機乗り

備忘録

問題

atcoder.jp

回答

import sys, os, math, bisect, itertools, collections, heapq, queue
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, M = il()
    X, Y = il()
    A, B = il(), il()

    time, ret = 0, 0
    while True:
        a = bisect.bisect_left(A, time)
        if len(A) == a: break
        time += abs(time-A[a]) + X

        b = bisect.bisect_left(B, time)
        if len(B) == b: break
        time += abs(time-B[b]) + Y

        ret += 1
    print(ret)


if __name__ == '__main__':
    main()

考え方

二分探索を用いて、
最も時間のロスが少ない飛行機に乗り続けるシミュレートを行う。

二分探索 - Wikipedia

与えられる飛行機のスケジュール配列に対して、
現在時刻がどこに位置するか二分探索モジュール(bisect)を用いて探索する。

Python標準ライブラリ:順序維持のbisect - Qiita

現在時刻の位置が配列の長さより小さい値の場合には、乗ることができる飛行機が存在しているため、
実際に乗った際の時間経過をシミュレート(現在時刻と飛行機に乗る時間の差分 + 移動時間)し、
A空港とB空港を往復した時点で結果に+1する。

現在時刻の位置が配列と同じ長さになった場合、
乗ることができる飛行機が存在しないため、シミュレートを終了する。