[백준/C/Python] 11723 - 집합

orangesnail·2024년 9월 7일

백준

목록 보기
23/169
post-thumbnail

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


구현 과정

집합의 기본적인 연산을 수행하는 문제다. 파이썬에는 set()를 사용해 집합을 만들 수 있지만, c에는 집합을 나타내는 특정한 자료형이 없기 때문에 배열을 사용해야 한다.

C에서의 구현

  1. set 배열을 선언하면서 모든 요소를 0으로 초기화해준다.
  2. 명령을 입력받을 것이기 때문에 입력받은 명령을 저장할 command 배열을 선언해준다.
  3. while (m--) 동안 command를 입력받고, strcmp() 으로 어떤 명령인지 판별 후 명령을 실행한다.

check 명령에 대한 설명을 보면 알 수 있듯이, 해당 요소가 추가되면 배열[해당 요소]의 값을 1로 설정한다. 삭제되면 값을 0으로 바꿔준다.

toggle의 경우에는 if문을 사용하는 대신, set[num] = !set[num] 으로 간단히 값을 바꿔줄 수 있다.

Python에서의 구현

  1. sys.stdin.readline 으로 input을 받는다.
  2. set() 을 이용해 빈 집합을 생성한다.
  3. for _ in range(m) 을 이용해 명령을 m번 입력받는다. 이때 명령을 입력받으면서 공백을 기준으로 split() 해서 명령과 숫자를 분리해 처리한다.

전체 코드

C

#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;
}

Python

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()
profile
초보입니다. 피드백 환영합니다 😗

0개의 댓글