[백준] 11723 - 집합
1. 문제
2. 개요
비어있는 공집합 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를 공집합으로 바꾼다.
3. 풀이 및 코드
3-1. 풀이
Python의 set, C#의 HashSet을 이용해 조건에 맞게 연산을 수행하면 된다.
3-2. Python
import sys
S = set()
M = int(sys.stdin.readline())
def DO(lst, s):
if lst[0] == 'add':
s.add(int(lst[1]))
elif lst[0] == 'remove':
if int(lst[1]) in s:
s.remove(int(lst[1]))
elif lst[0] == 'check':
print(int(int(lst[1]) in s))
elif lst[0] == 'toggle':
if int(lst[1]) in s:
s.remove(int(lst[1]))
else:
s.add(int(lst[1]))
elif lst[0] == 'all':
s = set([i for i in range(1, 21)])
else:
s.clear()
return s
for i in range(M):
command = list(sys.stdin.readline().split())
S = DO(command, S)
3-3. C#
namespace boj_11723
{
internal class Program
{
static StreamReader sr;
static StreamWriter sw;
static void Main(string[] args)
{
HashSet<int> S = new HashSet<int>();
sr = new StreamReader(Console.OpenStandardInput());
sw = new StreamWriter(Console.OpenStandardOutput());
int M = int.Parse(sr.ReadLine());
for (int i = 0; i < M; i++)
{
string[] command = sr.ReadLine().Split();
DO(command, S);
}
sw.Close();
}
static HashSet<int> DO(string[] com, HashSet<int> set)
{
switch(com[0])
{
case "add":
set.Add(int.Parse(com[1]));
break;
case "remove":
set.Remove(int.Parse(com[1]));
break;
case "check":
sw.WriteLine(Convert.ToInt32(set.Contains(int.Parse(com[1]))));
break;
case "toggle":
if (set.Contains(int.Parse(com[1])))
set.Remove(int.Parse(com[1]));
else
set.Add(int.Parse(com[1]));
break;
case "all":
set.Clear();
for (int i = 1; i < 21; i++)
set.Add(i);
break;
case "empty":
set.Clear();
break;
}
return set;
}
}
}
Comments