사용자 도구

사이트 도구


ps:problems:cses:1662

Subarray Divisibility

ps
링크cses.fi/…
출처CSES
문제 번호1662
문제명Subarray Divisibility
분류

누적합

시간복잡도O(n)
인풋사이즈n<=2*10^5
사용한 언어PyPy 3.9
제출기록0.10s
최고기록0.08s
해결날짜2026/05/07

풀이

  • 누적합 (Prefix sums) 을 이용하는 기본 유형의 문제
  • 누적합을 n으로 나눈 나머지들로 누적합 배열을 만든 다음, 같은 값을 갖는 인덱스 쌍의 개수를 세어주면 된다.
  • 기본 유형의 문제이지만 CSES 문제의 특성으로 Hash table hack 에 해당하는 데이터 셋이 들어있다. 같은 값을 갖는 인덱스들을 셀때, collections.Counter 나 dict등의 해시 기반 자료구조를 그냥 사용하면 TLE가 난다.
    • 여기에서는 값의 범위가 제한되어있기 때문에 그냥 리스트를 이용해서 카운팅하면 문제가 없다.

코드

collection.Counter를 사용해서 TLE가 나는 코드

problems/cses/q1662_tle.py
"""Solution code for "CSES 1662. Subarray Divisibility".

- Problem link: https://cses.fi/problemset/task/1662
- Solution link: http://www.teferi.net/ps/problems/cses/1662
"""

import collections


def main():
    n = int(input())
    a = [int(x) for x in input().split()]

    pref_sums = [x := 0] + [x := (x + a_i) % n for a_i in a]
    answer = sum(
        count * (count - 1) // 2
        for count in collections.Counter(pref_sums).values()
    )

    print(answer)


if __name__ == '__main__':
    main()

그냥 list를 이용해서 카운팅

problems/cses/q1662.py
"""Solution code for "CSES 1662. Subarray Divisibility".

- Problem link: https://cses.fi/problemset/task/1662
- Solution link: http://www.teferi.net/ps/problems/cses/1662
"""


def main():
    n = int(input())
    a = [int(x) for x in input().split()]

    count_by_cum_sum = [0] * n
    count_by_cum_sum[0] = 1
    cum_sum = 0
    answer = 0
    for x in a:
        cum_sum = (cum_sum + x) % n
        answer += count_by_cum_sum[cum_sum]
        count_by_cum_sum[cum_sum] += 1

    print(answer)


if __name__ == '__main__':
    main()

teflib.labs.intset.FrozenIntCounter를 사용

토론

댓글을 입력하세요:
Q V᠎ J C D
 
ps/problems/cses/1662.txt · 마지막으로 수정됨: 2026/05/19 02:36 저자 teferi