본문 바로가기

ALGORITHM/OTHER

[c++] 11723 집합 (비트마스크)

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

 

11723번: 집합

첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.

www.acmicpc.net

비트마스크에 대해 알아보자

& AND 비트가 모두 1이면 1
| OR 비트가 다르면 1
<< SHIFT (왼쪽) 비트를 왼쪽으로 이동
>> SHIFT (오른쪽) 비트를 오른쪽으로 이동
^ XOR 비트가 다르면 1, 같으면 0
~ NOT 비트를 반전

GOOD

 

BIT 변수는 0으로 초기화하고 사용하자

시간 초과가 난다면 입출력 시간을 줄이자

 

 

전체코드

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

int M, num, bit;
string input;

int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> M;
    while (M--) {
        cin >> input;
        if (input == "add") {
            cin >> num;
            bit |= (1 << num);
        }
        else if (input == "remove") {
            cin >> num;
            bit &= ~(1 << num);
        }
        else if (input == "check") {
            cin >> num;
            if (bit & (1 << num)) {
                cout << "1\n";
            }
            else {
                cout << "0\n";
            }
        }
        else if (input == "toggle") {
            cin >> num;
            if (bit & (1 << num))
                bit &= ~(1 << num);
            else
                bit |= (1 << num);
        }
        else if (input == "all") {
            bit = (1 << 21) - 1;
        }
        else if (input == "empty") {
            bit = 0;
        }
    }
    
    return 0;
}