새소식

반응형
250x250
Baekjoon/Gold

[백준] 구간 합 - 10986_나머지 합 구하기 Java[자바]

  • -
728x90
반응형

 

이번 문제도 합 배열을 이용해 해결해야 하는 문제이다.

 

합 배열을 구하는 방법은 

 

S[i] = S[i-1] + A[i] 이다.

 

위 예제를 기준으로 살펴보자.

 

합 배열은 [1, 3, 6, 7, 9]로 3으로 나눈 나머지의 배열은 [1, 0, 0, 1, 0]이다.

 

S[i] % M = 0이고 S[j] % M = 0이면 (S[i] - S[j]) % M = 0 이다.

 

따라서 S[i] % M == S[j] % M인 i와 j를 찾으면 되므로 나머지 배열의 같은 값을 가진 인덱스 중에서 2개를 고른 뒤 정답에 

 

추가해 주면 된다.

 

import java.io.*;
import java.util.*;

public class Main {
    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());
        long[] sumArr = new long[N + 1];
        long result = 0;
        long[] count = new long[M];
        for(int i = 1; i <= N; i++) {
            sumArr[i] = sumArr[i - 1] + Integer.parseInt(st.nextToken());
            count[(int)(sumArr[i] % M)]++;
            if((int)(sumArr[i] % M) == 0) result++;
        }
        for(int i = 0; i < M; i++) {
            if(count[i] > 1) {
                result += count[i] * (count[i] - 1) / 2;
            }
        }
        System.out.println(result);
        
    }
}
728x90
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.