- 모판을 만들어서 푸는 문제가 많이 나온다.
- 구간합을 미리 다 구해놓은 합 배열을 만든다.
https://www.acmicpc.net/problem/1292
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ1292_ans {
public static void main(String[] args) throws IOException {
int[] t = new int[1001];
// 0, 1, 2, 2, 3, 3, 3 ...
int idx = 1;
for (int i = 1; i < 1001; i++) {
for (int j = 0; j < i && idx < 1001; j++) {
t[idx++] = i;
}
}
int s[] = new int[1001];
// 0, 1, 3, 5, 8, 11, 14...
for (int i = 1; i < 1001; i++) {
s[i] = s[i - 1] + t[i];
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.println(s[b] - s[a-1]);
}
}
1000까지 미리 배열을 만들어 두어도 메모리 상 큰 차이는 없었다. 이렇게 하게 되면 값을 구할 때 O(1)로 구할 수 있다.
https://www.youtube.com/watch?v=2OQTm2fTi50
'문제 및 이론 정리 > 코딩 테스트' 카테고리의 다른 글
[코딩테스트] 확장 유클리드 호제법 접근 방법 (1) | 2024.11.28 |
---|---|
[코딩테스트] 모듈러(%) 분배 법칙 (0) | 2024.11.18 |
[코딩테스트] 오일러 피 (2) | 2024.10.05 |
[코딩테스트] 호제법, 소인수분해, 에라토스테네스의 체(소수 구하기) - 정수론 (0) | 2024.07.02 |