Home 백준 11660번 구간 합 구하기 5
Post
Cancel

백준 11660번 구간 합 구하기 5

정보

문제 바로가기 [클릭]

난이도: Silver1

관련 개념: #다이나믹 프로그래밍 #누적합


조건

시간 제한메모리 제한
1 초256 MB

문제

N×N개의 수가 N×N 크기의 표에 채워져 있다. (x1, y1)부터 (x2, y2)까지 합을 구하는 프로그램을 작성하시오. (x, y)는 x행 y열을 의미한다.

예를 들어, N = 4이고, 표가 아래와 같이 채워져 있는 경우를 살펴보자.

1
2
3
4
1	2	3	4
2	3	4	5
3	4	5	6
4	5	6	7

여기서 (2, 2)부터 (3, 4)까지 합을 구하면 3+4+5+4+5+6 = 27이고, (4, 4)부터 (4, 4)까지 합을 구하면 7이다.

표에 채워져 있는 수와 합을 구하는 연산이 주어졌을 때, 이를 처리하는 프로그램을 작성하시오.


입력

첫째 줄에 표의 크기 N과 합을 구해야 하는 횟수 M이 주어진다. (1 ≤ N ≤ 1024, 1 ≤ M ≤ 100,000) 둘째 줄부터 N개의 줄에는 표에 채워져 있는 수가 1행부터 차례대로 주어진다. 다음 M개의 줄에는 네 개의 정수 x1, y1, x2, y2 가 주어지며, (x1, y1)부터 (x2, y2)의 합을 구해 출력해야 한다. 표에 채워져 있는 수는 1,000보다 작거나 같은 자연수이다. (x1 ≤ x2, y1 ≤ y2)


출력

총 M줄에 걸쳐 (x1, y1)부터 (x2, y2)까지 합을 구해 출력한다.


예제 입출력 1

입력

1
2
3
4
5
6
7
8
4 3
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
2 2 3 4
3 4 3 4
1 1 4 4

출력

1
2
3
27
6
64

예제 입출력 2

입력

1
2
3
4
5
6
7
2 4
1 2
3 4
1 1 1 1
1 2 1 2
2 1 2 1
2 2 2 2

출력

1
2
3
4
1
2
3
4

코드(파이썬)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sys


n, m = map(int, sys.stdin.readline().split())
table = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

# 가로 누적합
for line in range(n):
    for y in range(n-1):
        table[line][y+1] += table[line][y]

# 가로 누적합을 더해 전체 누적합
for line in range(1, n):
    table[line][0] += table[line-1][0]
    for y in range(1, n):
        table[line][y] += table[line-1][y]
        
for _ in range(m):
    x1, y1, x2, y2 = map(lambda x: int(x)-1, sys.stdin.readline().split())
    
    dup = table[x1-1][y1-1] if x1 != 0 and y1 != 0 else 0
    up = table[x1-1][y2] if x1 != 0 else 0
    left = table[x2][y1-1] if y1 != 0 else 0
    r = table[x2][y2] - up - left + dup
        
    print(r)


특이사항

  • 구간 합에 대한 문제
    • 행별로 누적합 계산
    • 행별로 계산한 누적합을 더해 (1,1)에서 해당 좌표까지의 누적합 계산
    • 문제풀이
    • (3,3)~(5,5)합 = (5,5)누적합 - (2,5)누적합 - (5,2)누적합 + (2,2)누적합
  • 내 코드(71,520KB, 1,272ms)에 비해 우수한 코드(바로가기, 70,888KB, 868ms)와 비교
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      
      import sys
      from itertools import accumulate
      
      
      if __name__ == '__main__':
          n, m = map(int, sys.stdin.readline().split())
          arr = [[0] * (n+1)]
          for _ in range(n):
              arr.append([0] + list(accumulate(map(int, sys.stdin.readline().split()))))
      
          for i in range(1, n+1):
              for j in range(1, len(arr[0])):
                  arr[i][j] += arr[i-1][j]
      
          for _ in range(m):
              x1, y1, x2, y2 = map(int, sys.stdin.readline().split())
              ans = arr[x2][y2] - arr[x2][y1-1] - arr[x1-1][y2] + arr[x1-1][y1-1]
              print(ans)
      
      
      • itertools의 accumulate 함수 사용
      • 로직 동일

참고문헌

-

This post is licensed under CC BY 4.0 by the author.

백준 1753번 최단경로

백준 11444번 피보나치 수 6

Comments powered by Disqus.