PS
[비트마스킹] 11723 집합 c++구현
꽁이꽁설꽁돌
2024. 7. 17. 14:50
728x90
반응형
https://www.acmicpc.net/problem/11723
문제
문제 방향성
비트마스킹을 이용하면 쉽게 풀리는 문제이다.
몇번째 비트를 켜고 끄고 확인할지만 잘 해주면 된다.
참고
https://be-senior-developer.tistory.com/134
[비트 마스킹][c++] 개념과 활용 방법에 대해서 알아보자
목차 비트연산자의 기본 사용&비트단위로 AND 연산을 한다.|비트단위로 OR 연산을 한다.^비트단위로 XOR 연산을 한다.~피연산자의 모든 비트를 반전시킨다.피연산자의 비트 열을 왼쪽으로 이동시
be-senior-developer.tistory.com
문제 풀이 시 주의점
아래 코드 안써주면 시간초과 난다.
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
코드 구현
#include <iostream>
#include <vector>
using namespace std;
long long int N;
int S = 0;
void calculate(string order, int num) {
if (order == "add") {
S |= (1 << num);
} else if (order == "remove") {
S &= ~(1 << num);
} else if (order == "check") {
if (S & (1 << num)) {
cout << 1 << "\n";
} else {
cout << 0 << "\n";
}
} else if (order == "toggle") {
S ^= (1 << num);
} else if (order == "all") {
S = (1 << 21) - 1;
} else if (order == "empty") {
S = 0;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> N;
string order;
int num;
for (int i = 0; i < N; i++) {
cin >> order;
if (order == "add" || order == "remove" || order == "check" || order == "toggle") {
cin >> num;
} else {
num = 0; // "all"과 "empty" 명령어를 위한 기본값
}
calculate(order, num);
}
return 0;
}
반응형