[C++] 백준 11723 | 집합 : 비트마스킹

heige·2024년 1월 4일
0

BOJ

목록 보기
37/46
post-thumbnail

문제

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

풀이

#include <bits/stdc++.h>
using namespace std;
 
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    unsigned int s = 0;
    int m, n;
    string a ="";
    cin >> m;
    while(m--){
        cin >> a;
        if(a=="add"){
            cin >> n;
            s |= (1 << n);
        }else if(a == "remove"){
            cin >> n;
            s &= ~(1 << n);
        }else if(a== "check"){
            cin >> n;
            if(s & (1<<n)){
                cout << 1 << '\n';
            }else{
                cout << 0 << '\n';
            }
        }else if(a=="toggle"){
            cin >> n;
            s ^= (1<<n);
        }else if(a=="all"){
            s = (1 << 21) - 1;
        }else if(a == "empty"){
            s = 0;
        }
    }
    return 0;
}
  1. |= (1<<n) 로 원하는 원소 더해주고
  2. &= ~(1<<n) 을 이용하여 원소 제거
  3. if(s&(1<<n)) 를 이용해서 check 구현
  4. s ^= (1<<n) 를 이용해서 toggle 구현
  5. s = (1<<21) - 1 을 이용해서 all 구현
  6. s = 0 -> 공집합

💡배운 내용

비트마스킹

https://hagisilecoding.tistory.com/54
위 게시물을 참고하여 공부했다.

profile
웹 백엔드와 클라우드 정복을 위해 탄탄한 기반을 쌓아가고 있는 예비개발자입니다. 'IT You Up'은 'Eat You Up'이라는 표현에서 비롯되어, IT 지식을 끝까지 먹어치운다는 담고 있습니다.

0개의 댓글