- 문제 : https://www.acmicpc.net/problem/11723

 

문제 이해 

- 주어진 숫자만큼 주어진 명령어에 맞춰서 진행하면서 명령어가 check일 때 조건에 맞춰서 출력을 하는 문제다.

  1) 명령어가 add, remove, check, toggle의 옆에는 숫자 x가 띄어쓰기로 주어지고 

  2) 명령어가 all, empty인 경우는 숫자 없이 명령어만 주어진다. 

  -> 명령어에 맞춰서도 따로 분리를 해줘야 한다.

- 명령어 add에서 중복된 원소 추가는 안되기에 원소의 중복이 없는 set()을 사용했다. 

- 단계는 Silver5로 문제 자체는 그렇게 어렵지는 않았지만, 생각해야 할 게 꽤 많아서 시도를 많이 했던 문제다.

 

풀이 로직 

- 주어진 문자열을 temp에 저장하고, 원소가 2개면 command, number를 저장하고 원소가 1개라면 commad만 설정한다. 

- number는 string이므로 이것도 꼭 int()로 변경해줘야지 문제를 안 틀린다. 

- commad의 종류에 따라 각 케이스에 맞춰서 연산을 진행하면 된다.

 

정답 풀이1

아래 처럼 진행해도 정답이 뜨지만, 주어진 명령어 저장 및 처리가 분리되어있어 시간이 오래 걸리는 것 같다. 

import sys
input = sys.stdin.readline

arr = set()
for _ in range(int(input())):
    temp = input().split()
    if len(temp) == 2:
        command, number = temp[0], temp[1]
        number = int(number)
    else:
        command = temp[0]
    
    if command == 'add':
        arr.add(number)
        
    if command == 'remove':
        if number in arr:
            arr.remove(number)
            
    if command == 'check':
        if number in arr:
            print(1)
        else:
            print(0)
            
    if command == 'toggle':
        if number in arr:
            arr.remove(number)
        else:
            arr.add(number)
    if command == 'all':
        arr = set([i for i in range(1, 21)])
        
    if command == 'empty':
        arr = set()

 

정답 풀이2

이 풀이로 하면 시간이 좀 더 적게 걸리는데, 명령어가 주어졌을 때 바로 분기문을 명령어에 대한 처리를 하고, set에서 원소 제거시 remove()보다 discard()를 사용하는 점이 달랐다. 내용은 이 블로그를 참고했다.

import sys

m = int(sys.stdin.readline())
S = set()

for _ in range(m):
    temp = sys.stdin.readline().strip().split()
    
    if len(temp) == 1:
        if temp[0] == "all":
            S = set([i for i in range(1, 21)])
        else:
            S = set()
    
    else:
        func, x = temp[0], temp[1]
        x = int(x)

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

 

+ Recent posts