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;
}
'ALGORITHM > OTHER' 카테고리의 다른 글
[c++] 폰켓몬 (set, map) (0) | 2021.05.10 |
---|---|
[c++] 2042 구간 합 구하기 (세그먼트 트리) (0) | 2021.03.02 |
[c++] 1655 가운데를 말해요 (힙!) (2) | 2021.02.08 |
[c++] 11054 가장 긴 바이토닉 부분 수열 (이분탐색) (0) | 2021.02.03 |
[c++] 2805 나무 자르기 (이분탐색) (0) | 2021.01.29 |