11723번: 집합

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

www.acmicpc.net


 

비트마스킹을 배워서 사용하여 풀어보았다.

처음에 StringBuilder를 사용하지 않았더니 시간초과가 났다.

 

비트마스킹 연산

num |= (1<<index) // index자리에 1넣기
num &= ~(1<<index) // index자리에 0넣기
num ^= (1<<index) // index자리 토글하기
num = 0 // 모든 자리 0로 set
num = -1 // 모든 자리 1로 set

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int M, result, num;
static String command;
static StringTokenizer st;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
M = Integer.parseInt(br.readLine());
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
command = st.nextToken();
if (!(command.equals("all") || command.equals("empty"))) {
num = Integer.parseInt(st.nextToken());
}
if (command.equals("add")) {
result |= (1 << num);
} else if (command.equals("remove")) {
result &= ~(1 << num);
} else if (command.equals("check")) {
if ((result & (1 << num)) > 0) {
sb.append("1").append("\n");
} else {
sb.append("0").append("\n");
}
} else if (command.equals("toggle")) {
result ^= (1 << num);
} else if (command.equals("all")) {
result = -1;
} else if (command.equals("empty")) {
result = 0;
}
}
System.out.println(sb.toString());
}
}

'개발 > 알고리즘' 카테고리의 다른 글

[백준 3025] 돌 던지기  (1) 2021.09.08
[백준 2224] 명제 증명 (python)  (0) 2021.07.12
[백준 2638] 치즈 (python)  (0) 2021.06.02
[백준 16719] ZOAC (python)  (0) 2021.05.31
[백준 9934] 완전 이진 트리 (python)  (0) 2021.05.31
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기