[ ALGORITHM ]/[ 백 준 ]
[BAEKJOON] 11723번 : 집 합
HiStar__
2020. 9. 16. 19:18
문 제
소 스 코 드
#include <iostream>
#include <bitset>
// 32bit
// 0x 7 f f f ' f f f f; 16
// 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
constexpr int MAX_CHAR { 7 };
class Set {
public:
Set() : S{ 0 } {}
~Set() {};
void Add(const int& x) {
if (!((S >> x) & 1)) S |= (1 << x);
}
void Remove(const int& x) {
if (((S >> x) & 1)) S &= ~(1 << x);
}
bool Check(const int& x) {
if (((S >> x) & 1)) return true;
else return false;
}
void Toggle(const int& x) {
if (((S >> x) & 1)) S &= ~(1 << x);
else S |= (1 << x);
}
void All() {
S |= ~ (1);
}
void Empty() {
S &= 0;
}
private:
int S;
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cout.tie(NULL);
std::cin.tie(NULL);
int M;
std::cin >> M;
Set set;
char str[MAX_CHAR];
for (int i = 0; i < M; ++i) {
std::cin >> str;
int x;
switch (str[0]) {
case 'a':
// Add
if ('d' == str[1]) {
std::cin >> x;
set.Add(x);
}
// All
else set.All();
break;
case 'r':
// Remove
std::cin >> x;
set.Remove(x);
break;
case 'c':
// Check
std::cin >> x;
std::cout << set.Check(x) << '\n';
break;
case 't':
// Toggle
std::cin >> x;
set.Toggle(x);
break;
case 'e':
// Empty
set.Empty();
break;
default:
std::cout << " Default Input \n";
break;
}
}
return 0;
}
풀 이
-
비트 마스크 | 비트 연산
더보기
1 ~ 20 까지의 범위의 숫자를 사용하고, 메모리 제한이 있기 때문에 비트 마스크를 통하여 구현하여야 하는 문제이다.
32bit 컴퓨터에서 1byte는 4bit이다.
즉, 1 ~ 20 까지의 범위를 표현하는 변수형은 int 형 변수이다.
int는 4byte, 즉 32 bit로 1 ~ 32 까지를 표현 할 수 있다.
bitset 헤더를 추가 함으로써 2진으로 표현된 값을 출력 할 수 있다.
출 력 값
문 제 출 처
문제 링크 : www.acmicpc.net/problem/11723
11723번: 집합
첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.
www.acmicpc.net