Notice
Recent Posts
Recent Comments
Link
뮁이의 개발새발
[JAVA] 백준 11660 구간 합 구하기 5 (DP) 본문
https://subbak2.tistory.com/65
해당 블로그를 참조하였음 (설명 넘 잘되어있다ㅠㅠ)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class bj11660 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] arr = new int[N + 1][N + 1];
for (int i = 1; i <= N; i++) {
st = new StringTokenizer(in.readLine());
for (int j = 1; j <= N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int[][] dp = new int[N + 1][N + 1];
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + arr[i][j];
}
}
for (int k = 0; k < M; k++) {
st = new StringTokenizer(in.readLine());
int x1 = Integer.parseInt(st.nextToken());
int y1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
int y2 = Integer.parseInt(st.nextToken());
int sum = dp[x2][y2] - dp[x2][y1 - 1] - dp[x1 - 1][y2] + dp[x1 - 1][y1 - 1];
sb.append(sum + "\n");
}
System.out.println(sb);
}
}
더보기
<절망편>
반복문 두번 돌거나 이러한 방식을 쓰면 시간초과가 난다,,,,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class bj11660 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[][] arr = new int[N + 1][N + 1];
for (int i = 1; i <= N; i++) {
st = new StringTokenizer(in.readLine());
for (int j = 1; j <= N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < M; i++) {
st = new StringTokenizer(in.readLine());
int x1 = Integer.parseInt(st.nextToken());
int y1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
int y2 = Integer.parseInt(st.nextToken());
int ans = 0;
int temp = y1;
for (int j = x1; j <= x2; j++) {
if (temp > y2) {
temp = y1;
j = x1;
}
ans += arr[j][temp];
temp++;
}
sb.append(ans + "\n");
}
System.out.println(sb);
}
}
'Algorithm' 카테고리의 다른 글
[JAVA] Greedy 알고리즘 (with 이코테) (0) | 2021.12.09 |
---|---|
[JAVA] 백준 20291 파일 정리 (Map, TreeMap) (0) | 2021.12.09 |
[JAVA] 백준 7569 토마토 (BFS) (0) | 2021.11.09 |
[JAVA] 백준 15651 N과 M(3) (0) | 2021.11.09 |
[JAVA] 백준 4673 셀프 넘버 (0) | 2021.11.09 |
Comments