[백준] 11723번(집합)

·2023년 8월 1일

백준 문제풀이

목록 보기
105/159

백준 11723번


최종 제출 코드

import sys

input = sys.stdin.readline

# 1) 집합 원소의 범위는 정해져있음
# 2) 메모리 제한이 있음
# ⇒ 굳이 원소를 append하고 remove하는 방식으로 집합을 생성할 필요 없음
set = [False]*21

def check(x):
  if set[x]:
    print(1)
  else:
    print(0)
  return

def add(x):
  if set[x]:
    return
  set[x] = True
  return

def remove(x):
  if set[x]:
    set[x] = False
  return

def toggle(x):
  if set[x]:
    set[x] = False
  else:
    set[x] = True
  return

def all():
  global set
  for i in range(21):
    set[i] = True
  return

def empty():
  global set
  for i in range(21):
    set[i] = False
  return

n = int(input())

for i in range(n):
  arr = list(input().split())
  function = arr[0]
  # 인자가 주어질 때 ⇒ arr의 길이가 2 이상일 때만 argument 변수 생성
  if len(arr) > 1:
    argument = int(arr[1])
  
  if function == 'add':
    add(argument)
  elif function == 'remove':
    remove(argument)
  elif function == 'check':
    check(argument)
  elif function == 'toggle':
    toggle(argument)
  elif function == 'all':
    all()
  else:
    empty()

◼️ 처음에는 set를 일반적인 배열처럼 활용

  • 인수값을 append하고 remove하고 not in을 활용하는 식으로 문제 풀이
  • 메모리 초과

◼️어차피 원소의 범위는 1~20으로 정해져있음

  • set를 21개의 False 원소를 갖는 배열로 구성(index 0은 사용하지 않음)
  • 명령이 있을 때마다 인수를 인덱스로 전달하여 True/False 여부를 확인
  • 해결!
profile
백엔드 개발자가 되고 싶어요(22.8.15~)

0개의 댓글