Dev.baelanche

[백준 11659] 구간 합 구하기 4 본문

Data Structure & Algorithm/PS - JAVA

[백준 11659] 구간 합 구하기 4

baelanche 2019. 6. 16. 17:58
반응형

 

구간합 문제이다.

입력받은 배열 + 이전 배열을 더한 값을 저장하는 배열을 만들어 출력한다.

 

a[] 5 4 3 2 1  
psum[] 0 5 9 12 14 15

 

 

public class Main {
    
    public static void main(String[] args) throws Exception {
        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());
        
        int a[] = new int[n];
        int psum[] = new int[n+1];
        
        st = new StringTokenizer(br.readLine());
        for(int i=0; i<n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
            psum[i+1] = psum[i] + a[i];
        }
        
        for(int i=0; i<m; i++) {
            st = new StringTokenizer(br.readLine());
            int s = Integer.parseInt(st.nextToken());
            int e = Integer.parseInt(st.nextToken());
            System.out.println(psum[e] - psum[s-1]);
        }
    }
}

 

입력받은 수를 a 배열에 저장하여 풀었는데

바로 구간합 배열에 담아서 풀어도 상관없다.

반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 11441] 합 구하기  (0) 2019.06.16
[백준 11660] 구간 합 구하기 5  (0) 2019.06.16
[백준 1405] 미친 로봇  (0) 2019.06.16
[백준 17136] 색종이 붙이기  (0) 2019.06.13
[백준 2661] 좋은수열  (0) 2019.06.13
Comments