728x90
반응형
https://www.acmicpc.net/problem/11723
11723번: 집합
첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.
www.acmicpc.net
---------------------------------------------------핵심 알고리즘--------------------------------------------
bit을 활용한 set 조작
---------------------------------------------------풀이----------------------------------------------------
원소의 개수가 총 20개밖에 안되므로 array를 활용하였다.
bool로 선언하여 존재하면 true, 없으면 false로 만들었다.
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <stack>
#include <limits.h>
using namespace std;
int main(void){
FASTIO;
int M;
cin >> M;
bool set[21] = {false, };
while(M--){
string cmd;
cin >> cmd;
int x;
if(cmd == "add"){
cin >> x;
set[x] = true;
}
else if(cmd == "remove"){
cin >> x;
set[x] = false;
}
else if(cmd == "check"){
cin >> x;
cout << set[x] << "\n";
}
else if(cmd == "toggle"){
cin >> x;
set[x] ^= true;
}
else if(cmd == "all"){
for(int i = 1; i <= 20; i++){
set[i] = true;
}
}
else if(cmd == "empty"){
for(int i = 1; i <= 20; i++){
set[i] = false;
}
}
}
return 0;
}
---------------------------------------------------후기----------------------------------------------------
비트마스킹을 사용하는 알고리즘으로 되어 있었다.
2^20은 integer 범위 안에 들어오므로 bit를 조작해서 표현하는 것이 더 빠를 것 같긴 하다.
all이나 emtpy같은 경우에 나는 array의 원소를 전부 true나 false로 만들어 주었지만,
비트마스킹을 활용한다면 0이나 1로 바꿔주면 빠르게 될 것이다.
728x90
반응형
'알고리즘' 카테고리의 다른 글
[BOJ] 18870 좌표 압축 (0) | 2023.06.01 |
---|---|
[BOJ] 11726 2xn 타일링 (1) | 2023.06.01 |
[BOJ] 11399 ATM (0) | 2023.06.01 |
[BOJ] 9095 1, 2, 3 더하기 (0) | 2023.06.01 |
[BOJ] 7662 이중 우선순위 큐 (0) | 2023.06.01 |