Java
BOJ - 집합
개발자-H
2021. 9. 9. 07:17
https://www.acmicpc.net/problem/11723
11723번: 집합
첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.
www.acmicpc.net
- 비트마스킹을 활용한 문제이다.
- 문제의 입력 수가 3,000,000 이기에 System.out.println 함수를 사용 할 경우 시간 초과가 날 수 있다.
- StringBuilder 를 활용하면 된다!
import java.io.*;
import java.util.*;
public class Main {
public static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static int bit = 0;
private static StringBuilder builder = new StringBuilder();
public static void main(String[] args) throws Exception {
int M = Integer.parseInt(br.readLine());
StringTokenizer st;
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
String command = st.nextToken();
switch(command) {
case "add":
add(Integer.parseInt(st.nextToken()));
break;
case "remove":
remove(Integer.parseInt(st.nextToken()));
break;
case "check":
check(Integer.parseInt(st.nextToken()));
break;
case "toggle":
toggle(Integer.parseInt(st.nextToken()));
break;
case "all":
bit = 0x1FFFFE;
break;
case "empty":
bit = 0;
break;
}
}
System.out.println(builder);
}
public static void add(int position) {
bit |= (0x1 << position);
}
public static void remove(int position) {
bit &= ~(0x1 << position);
}
public static void check(int position) {
builder.append(((bit & (0x1 << position)) >> position) + "\n");
}
public static void toggle(int position) {
bit ^= (0x1 << position);
}
}