JuSeok

11723번

문제

비어있는 공집합 S가 주어졌을 때, 아래 연산을 수행하는 프로그램을 작성하시오.

add x: S에 x를 추가한다. (1 ≤ x ≤ 20) S에 x가 이미 있는 경우에는 연산을 무시한다.
remove x: S에서 x를 제거한다. (1 ≤ x ≤ 20) S에 x가 없는 경우에는 연산을 무시한다.
check x: S에 x가 있으면 1을, 없으면 0을 출력한다. (1 ≤ x ≤ 20)
toggle x: S에 x가 있으면 x를 제거하고, 없으면 x를 추가한다. (1 ≤ x ≤ 20)
all: S를 {1, 2, ..., 20} 으로 바꾼다.
empty: S를 공집합으로 바꾼다.
### 문제 해결 순서 1. 자바의 List를 활용하여 구현함. 2. 1, 0을 출력해주는 부분을 `System.out.println`으로 구현하니 시간초과 뜸. 3. StringBuilder를 이용하여 출력함. ```java import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer sb; StringBuilder answer = new StringBuilder(); List list = new ArrayList<>(); int n = Integer.parseInt(bf.readLine()); for (int i = 0; i < n; i++){ String temp = bf.readLine(); // all 일 경우 if(temp.equals("all")){ list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)); } // empty 일 경우 else if(temp.equals("empty")){ list = new ArrayList<>(); } else{ sb = new StringTokenizer(temp, " "); String be = sb.nextToken(); int num = Integer.parseInt(sb.nextToken()); if(be.equals("add")){ list.add(num); } else if(be.equals("remove")){ list.remove((Integer)num); } else if(be.equals("check")){ if (list.contains(num)) answer.append("1\n"); else answer.append("0\n"); } else if(be.equals("toggle")){ if (list.contains(num)) list.remove((Integer)num); else list.add(num); } } } System.out.print(answer); } } ```

Tags