๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/9780)
< Range Sum Query >
๋ฌธ์ ํ์ด
๋์ ํฉ์ ์ฌ์ฉํ๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class _9780_ { // Range Sum Query
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int t = Integer.parseInt(bf.readLine());
long arr[];
for (int i = 0; i < t; i++) {
bf.readLine();
st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
arr = new long[n];
st = new StringTokenizer(bf.readLine());
for (int j = 0; j < n; j++) {
arr[j] = Integer.parseInt(st.nextToken());
if (j > 0) {
arr[j] += arr[j - 1];
}
}
for (int j = 0; j < q; j++) {
st = new StringTokenizer(bf.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if (a > 0) {
bw.write(arr[b] - arr[a - 1] + "\n");
} else {
bw.write(arr[b] + "\n");
}
}
bw.write("\n");
}
bw.flush();
}
}
๋ณ์)
t : ํ ์คํธ ์ผ์ด์ค ๊ฐ์
arr : ๋์ ํฉ
n, q : ์ ์ ๊ฐ์, ์ค ๊ฐ์
a, b : ๊ตฌ๊ฐ
ํ ์คํธ ์ผ์ด์ค ๊ฐ์๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. ํ ์คํธ ์ผ์ด์ค ๊ฐ์๋งํผ ๋ค์ ๊ณผ์ ์ ๋ฐ๋ณตํ๋ค.
1) ์ ์ ๊ฐ์, ์ค ๊ฐ์๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค.
2) ์ ์ ๊ฐ์๋งํผ ์ ์๋ฅผ ์ ๋ ฅ๋ฐ์ ๋ฐฐ์ด์ ๋์ ํฉ์ ๊ตฌํด ์ ์ฅํ๋ค.
3) ์ค ๊ฐ์๋งํผ ๊ตฌ๊ฐ์ ์ ๋ ฅ๋ฐ์ ๊ตฌ๊ฐ์ ๋์ ํฉ์ ๊ตฌํด ์ถ๋ ฅํ๋ค.

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Baekjoon] 9834_Card (0) | 2026.03.25 |
|---|---|
| [Baekjoon] 11270_Disastrous Downtime (0) | 2026.03.24 |
| [Baekjoon] 18295_Ants (0) | 2026.03.19 |
| [Baekjoon] 13243_Non-decreasing subsegment (0) | 2026.03.18 |
| [Baekjoon] 6230_Buy One Get One Free (0) | 2026.03.16 |