
https://www.acmicpc.net/problem/11723
집합의 기본적인 연산을 수행하는 문제다. 파이썬에는 set()를 사용해 집합을 만들 수 있지만, c에는 집합을 나타내는 특정한 자료형이 없기 때문에 배열을 사용해야 한다.
while (m--) 동안 command를 입력받고, strcmp() 으로 어떤 명령인지 판별 후 명령을 실행한다. check 명령에 대한 설명을 보면 알 수 있듯이, 해당 요소가 추가되면 배열[해당 요소]의 값을 1로 설정한다. 삭제되면 값을 0으로 바꿔준다.
toggle의 경우에는 if문을 사용하는 대신, set[num] = !set[num] 으로 간단히 값을 바꿔줄 수 있다.
sys.stdin.readline 으로 input을 받는다.set() 을 이용해 빈 집합을 생성한다. for _ in range(m) 을 이용해 명령을 m번 입력받는다. 이때 명령을 입력받으면서 공백을 기준으로 split() 해서 명령과 숫자를 분리해 처리한다.#include <stdio.h>
#include <string.h>
int main() {
int set[21] = {0};
char command[10];
int m, num;
scanf("%d", &m);
while (m--) {
scanf("%s", command);
if (strcmp(command, "add") == 0) {
scanf("%d", &num);
set[num] = 1;
}
else if (strcmp(command, "remove") == 0) {
scanf("%d", &num);
set[num] = 0;
}
else if (strcmp(command, "check") == 0) {
scanf("%d", &num);
printf("%d\n", set[num]);
}
else if (strcmp(command, "toggle") == 0) {
scanf("%d", &num);
set[num] = !set[num];
}
else if (strcmp(command, "all") == 0) {
for (int i = 0; i < 21; i++)
set[i] = 1;
}
else if (strcmp(command, "empty") == 0) {
for (int i = 0; i < 21; i++)
set[i] = 0;
}
}
return 0;
}
import sys
input = sys.stdin.readline
m = int(input())
s = set()
for _ in range(m):
opr = input().split()
command = opr[0]
if command == 'add':
x = int(opr[1])
s.add(x)
elif command == 'remove':
x = int(opr[1])
s.discard(x)
elif command == 'check':
x = int(opr[1])
print(1 if x in s else 0)
elif command == 'toggle':
x = int(opr[1])
if x in s:
s.discard(x)
else:
s.add(x)
elif command == 'all':
s = set(range(1, 21))
elif command == 'empty':
s.clear()