알고리즘/백준

[백준 11723] 집합 (with Python / 구현)

baegopeunGom 2023. 9. 10. 23:18
문제링크

https://www.acmicpc.net/problem/11723

 

11723번: 집합

첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.

www.acmicpc.net

문제설명

 

문제

비어있는 공집합 S가 주어졌을 때, 아래 연산을 수행하는 프로그램을 작성하시오.

  • add x: S에 x를 추가한다. (1 ≤ x ≤ 20) S에 x가 이미 있는 경우에는 연산을 무시한다.
  • remove x: S에서 x를 제거한다. (1 ≤ x ≤ 20) S에 x가 없는 경우에는 연산을 무시한다.
  • check x: S에 x가 있으면 1을, 없으면 0을 출력한다. (1 ≤ x ≤ 20)
  • toggle x: S에 x가 있으면 x를 제거하고, 없으면 x를 추가한다. (1 ≤ x ≤ 20)
  • all: S를 {1, 2, ..., 20} 으로 바꾼다.
  • empty: S를 공집합으로 바꾼다.

입력

첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다.

둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.

출력

check 연산이 주어질때마다, 결과를 출력한다.

 

문제풀이

어렵지 않게 구현 가능한 문제이다.

 

나는 파이썬의 딕셔너리를 이용하여 풀었지만,

set을 이용하면 더 편할 것 같다.

 

코드
import sys
input = sys.stdin.readline

N = int(input())
dict = {}

def add(x):
    if x not in dict:
        dict[x] = 1

def remove(x):
    if x in dict:
        del dict[x]

def check(x):
    if x in dict:
        print(1)
    else:
        print(0)

def toggle(x):
    if x in dict:
        del dict[x]
    else:
        dict[x] = 1

def all():
    dict.clear()
    for i in range(20):
        dict[i+1] = 1

def empty():
    dict.clear()

for i in range(N):
    num = 0
    arr = input().split()
    
    if len(arr) == 1:
        command = arr[0]
    else:
        command, num = arr[0], arr[1]

    if not num:
        if command == 'all':
            all()
        elif command == 'empty':
            empty()
    else:
        N = int(num)
        if command == 'add':
            add(N)
        elif command == 'check':
            check(N)
        elif command == 'remove':
            remove(N)
        elif command == 'toggle':
            toggle(N)

또 다른 정답코드

import sys
input = sys.stdin.readline

S = set()
N = int(input())

for _ in range(N):
    arr = input().split()

    if len(arr) == 1:
        command = arr[0]
        if command == 'all':
            S = set([i for i in range(1, 21)])
        else:
            S = set()
    else:
        command, num = arr[0], arr[1]
        x = int(num)

        if command == 'add':
            S.add(x)
        elif command == 'remove':
            S.discard(x)
        elif command == 'check':
            print(1 if x in S else 0)
        elif command == 'toggle':
            if x in S:
                S.discard(x)
            else:
                S.add(x)