Post

[백준/코틀린] 11723번: 집합

실버 5

링크

11723번: 집합

풀이

비트마스킹으로 집합을 표현합니다.
주어진 연산을 비트 연산으로 구현합니다.


[set]

집합에 특정 원소를 추가합니다.
X OR 0 = X / X OR 1 = 1

\[\begin{array}{lcl} \ & \texttt{XXXX XXXX} \\ \text{OR} & \texttt{0001 0000} \\ \hline \ & \texttt{XXX1 XXXX} \end{array}\]


[clear]

집합에서 특정 원소를 제거합니다.
X AND 0 = 0 / X AND 1 = X

\[\begin{array}{lcl} \ & \texttt{XXXX XXXX} \\ \text{AND} & \texttt{1110 1111} \\ \hline \ & \texttt{XXX0 XXXX} \end{array}\]


[check]

집합에 특정 원소가 있는지 확인합니다.
X AND 0 = 0 / X AND 1 = X

\[\begin{array}{lcl} \ & \texttt{XXXX XXXX} \\ \text{AND} & \texttt{0001 0000} \\ \hline \ & \texttt{000X 0000} \end{array}\]


[toggle]

집합에 특정 원소가 집합에 있으면 제거하고, 없으면 추가합니다.
X XOR 0 = X / X XOR 1 = ~X

\[\begin{array}{lcl} \ & \texttt{XXX0 XXXX} \\ \text{XOR} & \texttt{0001 0000} \\ \hline \ & \texttt{XXX1 XXXX} \end{array}\] \[\begin{array}{lcl} \ & \texttt{XXX1 XXXX} \\ \text{XOR} & \texttt{0001 0000} \\ \hline \ & \texttt{XXX0 XXXX} \end{array}\]


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fun main() = with(StringBuilder()) {
  var s = 0

  repeat(readln().toInt()) {
    val op = readln().split(" ")
    val x = 1 shl (op.last().toIntOrNull() ?: 0)

    s = when (op[0]) {
      "add" -> s or x
      "remove" -> s and x.inv()
      "check" -> s.also { appendLine(if (s and x > 0) 1 else 0) }
      "toggle" -> s xor x
      "all" -> 0.inv()
      else -> 0
    }
  }

  println(toString())
}

This post is licensed under CC BY 4.0 by the author.