just do it

구간 합 구하기/백준 11659번(java) 본문

자료구조&알고리즘/코딩테스트

구간 합 구하기/백준 11659번(java)

밍풀 2022. 9. 15. 09:15

로직

숫자 개수, 질의 개수 저장하기

 

숫자개수만큼 반복

합 배열 생성 

 

질의개수만큼 반복

질의범위 받기

구간합 출력하기 

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
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        int A[]=new int[N];
        int S[]=new int[N+1];
        S[0]=0;
        
        for(int i=0;i<N;i++) {
            A[i]=sc.nextInt();
            S[i+1]=S[i]+A[i];
        }
 
        
        for(int i=0;i<M;i++) {
            int a=sc.nextInt();
            int b=sc.nextInt();
            
            System.out.println(S[b]-S[a-1]);
        }
        
        
 
        
        
    }
}
 
cs

 

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class Main {
 
    public static void main(String[] args) throws IOException{
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
        int suNo= Integer.parseInt(stringTokenizer.nextToken());
        int quizNo=Integer.parseInt(stringTokenizer.nextToken());
        long []S= new long[suNo+1];
        stringTokenizer = new StringTokenizer(bufferedReader.readLine());
        
        for(int i=1;i<=suNo;i++) {
            S[i]=S[i-1]+Integer.parseInt(stringTokenizer.nextToken());
        }
        
        for(int q=0;q<quizNo;q++) {
            stringTokenizer = new StringTokenizer(bufferedReader.readLine());
            int i = Integer.parseInt(stringTokenizer.nextToken());
            int j = Integer.parseInt(stringTokenizer.nextToken());
            System.out.println(S[j]-S[i-1]);
        }
    
 
    }
 
}
 
cs

 

+

int, long 등 숫자배열을 선언만 해놓고 아무것도 들어가 있지 않을때, 출력하면 그냥 0이 나온다.

따라서 S배열을 구할때 위 코드에서 S[0]=0을 따로 지정해 줄 필요가 없다.