목차

Rest Stops

ps
링크acmicpc.net/…
출처BOJ
문제 번호15748
문제명Rest Stops
레벨골드 5
분류

그리디

시간복잡도O(n)
인풋사이즈n<=10^5
사용한 언어Python
제출기록46980KB / 184ms
최고기록184ms
해결날짜2022/04/13

풀이

코드

코드 1 - O(nlogn)

"""Solution code for "BOJ 15748. Rest Stops".

- Problem link: https://www.acmicpc.net/problem/15748
- Solution link: http://www.teferi.net/ps/problems/boj/15748

Tags: [Greedy]
"""

import sys
import operator


def main():
    # pylint: disable=unused-variable
    L, N, rF, rB = [int(x) for x in sys.stdin.readline().split()]
    stops = [[int(x) for x in sys.stdin.readline().split()] for _ in range(N)]

    answer = 0
    prev_pos = 0
    for pos, tastiness in sorted(stops,
                                 key=operator.itemgetter(1),
                                 reverse=True):
        if pos > prev_pos:
            answer += tastiness * (rF - rB) * (pos - prev_pos)
            prev_pos = pos

    print(answer)


if __name__ == '__main__':
    main()

코드 2 - O(n)

"""Solution code for "BOJ 15748. Rest Stops".

- Problem link: https://www.acmicpc.net/problem/15748
- Solution link: http://www.teferi.net/ps/problems/boj/15748

Tags: [Greedy]
"""

import itertools
import sys

INF = float('inf')


def main():
    # pylint: disable=unused-variable
    L, N, rF, rB = [int(x) for x in sys.stdin.readline().split()]
    stops = [[int(x) for x in sys.stdin.readline().split()] for _ in range(N)]

    stops_to_rest = []
    max_tastiness = 0
    for pos, tastiness in reversed(stops):
        if tastiness > max_tastiness:
            max_tastiness = tastiness
            stops_to_rest.append((pos, tastiness))
    stops_to_rest.append((0, INF))

    speed_diff = rF - rB
    answer = sum(s2[1] * (s2[0] - s1[0]) * speed_diff
                 for s1, s2 in itertools.pairwise(reversed(stops_to_rest)))
    print(answer)


if __name__ == '__main__':
    main()