[BOJ] #13144 List of Unique Numbers (Python)

    ๋ฐ˜์‘ํ˜•

    ๐ŸŒฑ ๋ฌธ์ œ

     

    13144๋ฒˆ: List of Unique Numbers

    ๊ธธ์ด๊ฐ€ N์ธ ์ˆ˜์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ์ˆ˜์—ด์—์„œ ์—ฐ์†ํ•œ 1๊ฐœ ์ด์ƒ์˜ ์ˆ˜๋ฅผ ๋ฝ‘์•˜์„ ๋•Œ ๊ฐ™์€ ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ๋“ฑ์žฅํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์—ฌ๋ผ.

    www.acmicpc.net

     

    ๐ŸŒฑ ํ’€์ด

    0. ์ž…๋ ฅ ๋ฐ›๊ธฐ

    n = int(input().rstrip())
    num_list = list(map(int, input().split()))

    ์ˆ˜์—ด์˜ ๊ธธ์ด์™€ ์ˆ˜์—ด์˜ ์›์†Œ ๊ฐ’๋“ค์„ ์ž…๋ ฅ๋ฐ›์Šต๋‹ˆ๋‹ค.

    1. ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™”

    result = 0
    start, end = 0, 0
    seq = [False] * 1000001
    • ํˆฌํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด ํ’€๊ธฐ ์œ„ํ•ด num_list์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ start์™€ end๋ฅผ ๊ฐ๊ฐ 0์œผ๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ค๋‹ˆ๋‹ค.
    • seq์— ์ˆ˜์—ด์— ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ“๊ฐ’์ธ 100000 ํฌ๊ธฐ์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ์ˆซ์ž๊ฐ€ ์ค‘๋ณต๋˜์—ˆ๋Š”์ง€ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค.

    2. ํˆฌํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜

    while start < n and end < n:
        if not seq[num_list[end]]:      # start๋ถ€ํ„ฐ end๊นŒ์ง€ ์ค‘๋ณต ์ˆซ์ž ์—†์œผ๋ฉด
            seq[num_list[end]] = True
            end += 1
            result += (end - start)     # end๋ฅผ ํฌํ•จํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ˆ˜์—ด์˜ ๊ฐœ์ˆ˜
        else:
            seq[num_list[start]] = False
            start += 1
    • start์™€ end๊ฐ€ ๋ชจ๋‘ ๋งˆ์ง€๋ง‰ ์›์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.
    • ๋งŒ์•ฝ end๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ˆซ์ž๊ฐ€ ์•„์ง๊นŒ์ง€ ๋‚˜์˜ค์ง€ ์•Š์•˜๋‹ค๋ฉด, start๋ถ€ํ„ฐ end๊นŒ์ง€ end๋ฅผ ํฌํ•จํ•˜๋Š” ์ˆ˜์—ด์˜ ์กฐํ•ฉ์˜ ๊ฐœ์ˆ˜์ธ end + 1 - start๋ฅผ result์— ๋”ํ•˜๊ณ , end๋Š” ์ „์ง„์‹œํ‚ต๋‹ˆ๋‹ค.
      ์˜ˆ๋ฅผ ๋“ค์–ด, [1, 2, 3, 1, 2] ์ˆ˜์—ด์—์„œ start๊ฐ€ 0์ด๊ณ , end๊ฐ€ 2์ผ๋•Œ, end๋ฅผ ํฌํ•จํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์กฐํ•ฉ์€ [3], [2, 3], [1, 2, 3]์œผ๋กœ 3๊ฐœ(end + 1 - start = 2 + 1- 0 = 3) ์ž…๋‹ˆ๋‹ค.
      end๋ฅผ ๋ฏธ๋ฆฌ ์ „์ง„์‹œ์ผœ๋†“์œผ๋ฉด result๋ฅผ ๊ณ„์‚ฐํ•  ๋•Œ +1์„ ์ƒ๋žตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • ๋งŒ์•ฝ end๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ˆ˜๊ฐ€ ์ด๋ฏธ ๋‚˜์™”๋‹ค๋ฉด(์ค‘๋ณต๋˜์—ˆ๋‹ค๋ฉด), start๋ฅผ ์ „์ง„์‹œํ‚ต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ˜„์žฌ์˜ start๋Š” ์•ˆ๋‚˜์˜จ ๊ฐ’์œผ๋กœ ์ทจ๊ธ‰ํ•ด์ฃผ์–ด์•ผ ํ•˜๋ฏ€๋กœ seq์—์„œ start๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ˆ˜๋ฅผ False ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

     

    ๐ŸŒฑ ์ฝ”๋“œ

    # !/usr/bin/env python
    # -*- coding: utf-8 -*-
    # boj 13144 List of Unique Numbers
    
    import sys
    from collections import defaultdict
    
    num_dict = defaultdict(list)
    input = sys.stdin.readline
    n = int(input().rstrip())
    
    num_list = list(map(int, input().split()))
    
    result = 0
    start, end = 0, 0
    seq = [False for _ in range(1000001)]
    while start < n and end < n:
        if not seq[num_list[end]]:      # start๋ถ€ํ„ฐ end๊นŒ์ง€ ์ค‘๋ณต ์ˆซ์ž ์—†์œผ๋ฉด
            seq[num_list[end]] = True
            end += 1
            result += (end - start)     # end๋ฅผ ํฌํ•จํ•˜์—ฌ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ˆ˜์—ด์˜ ๊ฐœ์ˆ˜
        else:
            seq[num_list[start]] = False
            start += 1
    
    print(result)
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€