사용자 도구

사이트 도구


ps:problems:boj:11997

Load Balancing (Silver)

ps
링크acmicpc.net/…
출처BOJ
문제 번호11997
문제명Load Balancing (Silver)
레벨골드 4
분류

누적합

시간복잡도O(n^2)
인풋사이즈n<=1000
사용한 언어Python
제출기록55836KB / 688ms
최고기록916ms
해결날짜2022/05/30
태그

[라이] 구간합 배열

풀이

  • 11990의 쉬운 버전.
  • N의 범위가 1000이하이므로, 모든 가능한 x좌표와 y좌표에 대해서 그점을 중심으로 가로펜스와 세로펜스를 그었을때의 M값을 계산해보고, 그중에서 최소 M값을 찾는 O(N^2) 알고리즘으로도 통과된다.
  • 물론 여기에서 M값을 계산하는 것은 O(1)에 처리할수 있어야 한다. O(N)만큼의 메모리만을 사용해서 계산하게 하는 것도 가능은 하지만, 같은 X좌표에 있는 소들과 같은 Y좌표에 있는 소들을 정확히 처리하면서 구현하려면 코드가 꽤 복잡해진다.
  • 차라리 메모리를 좀 많이 쓰고 전처리 시간이 걸리더라도, X좌표와 Y좌표들을 모두 좌표압축하고, 각 좌표의 소의 갯수를 1과 0으로 표현하는 2d 테이블을 만든 다음에, 2d 누적합을 구해서 계산하는게 심플하다.
  • 총 시간복잡도는 좌표압축에 O(NlogN), 2D 누적합 계산에 O(N^2), 모든 좌표에 대해서 M값을 계산하는것에 O(N^2)이 걸리므로 총 O(N^2).

코드

"""Solution code for "BOJ 11997. Load Balancing (Silver)".

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

import sys

INF = float('inf')


def create_2d_prefix_sum(nums):
    prefix_sum = [[0] * (len(nums[0]) + 1)]
    for row in nums:
        prefix_sum.append([ps := 0] +
                          [(ps := ps + num) + p
                           for num, p in zip(row, prefix_sum[-1][1:])])
    return prefix_sum


def main():
    N = int(sys.stdin.readline())
    x_coords, y_coords = [], []
    for _ in range(N):
        x, y = [int(x) for x in sys.stdin.readline().split()]
        x_coords.append(x)
        y_coords.append(y)

    x_comp_map = {x: i for i, x in enumerate(sorted(set(x_coords)))}
    y_comp_map = {y: i for i, y in enumerate(sorted(set(y_coords)))}
    nums = [[0] * len(x_comp_map) for _ in y_comp_map]
    for x_i, y_i in zip(x_coords, y_coords):
        nums[y_comp_map[y_i]][x_comp_map[x_i]] = 1

    prefix_sum = create_2d_prefix_sum(nums)
    bottom_row = prefix_sum[-1]
    total = bottom_row[-1]
    answer = INF
    for row in prefix_sum:
        ps_r = row[-1]
        for ps_rc, ps_c in zip(row, bottom_row):
            up_left = ps_rc
            up_right = ps_r - up_left
            down_left = ps_c - up_left
            down_right = total - up_right - down_left - up_left
            answer = min(answer, max(up_left, up_right, down_left, down_right))
            
    print(answer)


if __name__ == '__main__':
    main()

토론

댓글을 입력하세요:
B W I E O
 
ps/problems/boj/11997.txt · 마지막으로 수정됨: 2022/05/31 15:26 저자 teferi