Little Jay

[C++] 백준 11723번 - 집합 본문

알고리즘/BOJ

[C++] 백준 11723번 - 집합

Jay, Lee 2021. 8. 14. 15:41

비트마스킹

처음으로 비트마스킹에 대해서 다뤘던 문제이다.

처음에는 무지성으로 벡터를 이용해서 풀면 될 줄 알았지만,

백준에 달려있는 태그랑 메모리를 보니까 이거는 벡터로 풀면 안되겠다는 것을 깨달았다.

자바를 배울때 stream 연산자를 배워놔서 조금은 쉽게 공부하고 풀 수 있었다.

 

#include <iostream>
#include <string>
using namespace std;

int main() {

	ios::sync_with_stdio(false);
	cin.tie(0);

	long long n;
	cin >> n;

	string s;
	int x, BIT = 0;

	for (long long i = 0; i < n; i++) {
		cin >> s;
		if (s == "add") {
			cin >> x;
			BIT |= (1 << x);
		}
		else if (s == "remove") {
			cin >> x;
			BIT &= ~(1 << x);
		}
		else if (s == "check") {
			cin >> x;
			if (BIT & (1 << x))
				cout << 1 << '\n';
			else
				cout << 0 << '\n';
		}
		else if (s == "toggle") {
			cin >> x;
			BIT ^= (1 << x);
		}
		else if (s == "all") {
			BIT = (1 << 21) - 1;
		}
		else if (s == "empty") {
			BIT = 0;
		}
	}

	return 0;
}
Comments