ABOUT ME

Today
-
Yesterday
-
Total
-
  • 11723. 집합
    Algorithm/Baekjoon 2023. 2. 27. 23:54

    문제 자체는 어렵지 않으나, 새로운 방법이 있어 기록해두고자 작성한다.

     

    처음엔 정말 직관적으로 set 자료형을 사용해서 정직하게 구현하였다.

    # 집합
    import sys
    input = sys.stdin.readline
    
    def set_add(s, x) :
        s.add(x)
        return s
    
    def set_remove(s, x) :
        try :
            s.remove(x)
            return s
        except :
            return s
    
    def set_check(s, x) :
        if x in s :
            print("1")
        else :
            print("0")
    
    def set_toggle(s, x) :
        if x in s :
            s.remove(x)
        else :
            s.add(x)
        return s
    
    def set_all() :
        return {i for i in range(1,21)}
    
    def set_empty() :
        return set()
    
    s = set()
    m = int(input())
    
    for i in range(m) :
        command = input().split()
        if command[0] == 'add' :
            s = set_add(s, int(command[1]))
        elif command[0] == 'remove' :
            s = set_remove(s, int(command[1]))
        elif command[0] == 'check' :
            set_check(s, int(command[1]))
        elif command[0] == 'toggle' :
            s = set_toggle(s, int(command[1]))
        elif command[0] == 'all' :
            s = set_all()
        elif command[0] == 'empty' :
            s = set_empty()

    그런데 찾아보니까 set 을 사용해서 매번 연산을 하면 시간이 오래 걸린다고 한다. 

    따라서 set을 사용하지 않고, 문제에서 원소가 될 수 있는 x의 범위가 작으므로 각 숫자가 집합에 들어있는지를 판단하는 리스트를 이용하는 방법을 생각해볼 수 있다.

    특정 숫자를 집합에 넣어야 할 때는 해당 요소의 값을 True로 변경하고, 

    특정 숫자를 집합에서 제거해야 할 때에는 해당 요소의 값을 False로 변경하는 식이다.

     

    import sys
    
    input = sys.stdin.readline
    
    set_list = [False for _ in range(21)]
    
    m = int(input())
    
    for i in range(m) :
        command = input().split()
        if command[0] == 'add' :
            set_list[int(command[1])] = True
        elif command[0] == 'remove' :
            set_list[int(command[1])] = False
        elif command[0] == 'check' :
            print(int(set_list[int(command[1])]))
        elif command[0] == 'toggle' :
            set_list[int(command[1])] = not set_list[int(command[1])]
        elif command[0] == 'all' :
            set_list = [True for _ in range(21)]
        elif command[0] == 'empty' :
            set_list = [False for _ in range(21)]

     

     

    'Algorithm > Baekjoon' 카테고리의 다른 글

    1205. 등수 구하기  (0) 2023.03.06
    1009. 분산처리  (0) 2023.03.01
    1018. 체스판 다시 칠하기  (0) 2023.02.20
    20302. 민트초코  (0) 2023.02.14
    2436. 공약수  (0) 2023.02.11

    댓글

Designed by nanometre380.