백준 11723 - 집합

황재진·2024년 7월 21일

백준

목록 보기
44/54

공집합 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를 공집합으로 바꾼다.

숫자가 1~20 사이의 수만 들어오기 때문에 해당 크기의 bool 배열을 만들어서 숫자가 있다면 1, 없다면 0으로 설정해 이를 해결할 수 있습니다. 마치 2진수를 활용하는 것처럼 보여 비트마스크 방식으로 해결한다고 한다네요.

#include <iostream>

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);

	int M;
	std::cin >> M;

	bool bitarr[21];
	for (int i = 0; i < 21; i++)
		bitarr[i] = 0;

	for (int i = 0; i < M; i++)
	{
		std::string str;
		std::cin >> str;

		if (str.compare("add") == 0)
		{
			int temp;
			std::cin >> temp;
			bitarr[temp] = 1;
		}
		else if (str.compare("remove") == 0)
		{
			int temp;
			std::cin >> temp;
			bitarr[temp] = 0;
		}
		else if (str.compare("check") == 0)
		{
			int temp;
			std::cin >> temp;
			std::cout << bitarr[temp] << "\n";
		}
		else if (str.compare("toggle") == 0)
		{
			int temp;
			std::cin >> temp;
			bitarr[temp] = !bitarr[temp];
		}
		else if (str.compare("all") == 0)
		{
			for (int i = 0; i < 21; i++)
				bitarr[i] = 1;
		}
		else if (str.compare("empty") == 0)
		{
			for (int i = 0; i < 21; i++)
				bitarr[i] = 0;
		}
	}

	return 0;
}
profile
프로그래밍, 쉐이더 등 이것저것 다해보는 게임 개발자입니다

0개의 댓글