Korean English Japanese Chinese (Simplified) Chinese (Traditional)

 

 

 

 

 

11659번: 구간 합 구하기 4

첫째 줄에 수의 개수 N과 합을 구해야 하는 횟수 M이 주어진다. 둘째 줄에는 N개의 수가 주어진다. 수는 1,000보다 작거나 같은 자연수이다. 셋째 줄부터 M개의 줄에는 합을 구해야 하는 구간 i와 j

www.acmicpc.net

 

 

난이도: 실버 3

풀이: 먼저 입력받은 값을 배열로 저장하고, 합배열을 생성한다. 그리고 합배열을 사용하여, 더 빠르게 연산을 수행할 수 있다.

 

 

 

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
28
29
30
31
32
33
34
35
36
import java.util.*;
import java.io.*;
 
public class P11659 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N        = Integer.parseInt(st.nextToken());
        int M        = Integer.parseInt(st.nextToken());
        
        st            = new StringTokenizer(br.readLine());
        int A[]    = new int[N+1];
        for (int i = 1; i <= N; i++) {
            A[i] = Integer.parseInt(st.nextToken());
        }
        
        int S[]     = new int[N+1];
        S[1]        = A[1];
        for (int i = 2; i <= N; i++) {
            S[i] = S[i-1+ A[i];
        }
        
        int sum;
        for (int i = 1; i <= M; i ++) {
            st    = new StringTokenizer(br.readLine());
            int H        = Integer.parseInt(st.nextToken());
            int W     = Integer.parseInt(st.nextToken());
            sum        = S[W] - S[H-1];
            
            System.out.println(sum);
        }
        
    }
}
 
cs

 

 

If you like this post, please give me a ❤️...!
 
✰Popular Posts✰
✰Recent Posts✰
 

❤ from Seoul, Daejeon, Tokyo, Fukuoka