김진영이 듣도 못한 사람의 명단과, 보도 못한 사람의 명단이 주어질 때, 듣도 보도 못한 사람의 명단을 구하는 프로그램을 작성하시오.
쉽게 보자면 듣도 못한 사람 -A, 보도 못한 사람 -B
문제에서 요구하는 것- A∩B
생각해야할 부분은, A 와 B 중 크기가 큰 집합을 기준으로 처리해야한다는 것이다.
따라서 크기를 비교하여 작은 집합에 큰 집합의 원소가 있는지 Contains 처리하여 참이라면 별도의 리스트에 추가해준다.
리스트는 Sort 함수를 이용하여 사전순으로 정렬해준다.
이 때, 어차피 문제에서는 동일한 문자열이 들어오지 않기 때문에 CompareTo가 0이 나올 경우는 생략한다.
namespace SongE
{
public class Program
{
static void Main(string[] args)
{
using var input = new System.IO.StreamReader(Console.OpenStandardInput());
using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());
int[] n = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));
Dictionary<string, int> A = new();
Dictionary<string, int> B = new();
for (int i = 0; i < n[0]; i++)
{
A.Add(input.ReadLine(), i);
}
for (int i = 0; i < n[1]; i++)
{
B.Add(input.ReadLine(), i);
}
int standard = Math.Max(n[0], n[1]);
List<string> list = new List<string>();
for (int i = 0; i < standard; i++)
{
if (n[0] < n[1])
{
string s = B.ElementAt(i).Key;
if (A.ContainsKey(s))
{
list.Add(s);
}
}
else
{
string s = A.ElementAt(i).Key;
if (B.ContainsKey(s))
{
list.Add(s);
}
}
}
list.Sort((a,b) => { return a.CompareTo(b); });
print.WriteLine(list.Count);
foreach(string name in list) print.WriteLine(name);
}
}
}
시간초과요...
사실 작성하면서 for문이 너무 많아 예상하긴 했다.
그래서 찾아보았더니 Enumerable.Intersect 라는 함수가 있는 것을 찾았다.
또한 맵이라는 단어에 집착한 나머지 필요없는 값이 있어야 하는 딕셔너리를 사용했기 때문에
리스트로 변경해주었다.
namespace SongE
{
public class Program
{
static void Main(string[] args)
{
using var input = new System.IO.StreamReader(Console.OpenStandardInput());
using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());
int[] n = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));
List<string> A = new();
List<string> B = new();
for (int i = 0; i < n[0]; i++)
{
A.Add(input.ReadLine());
}
for (int i = 0; i < n[1]; i++)
{
B.Add(input.ReadLine());
}
IEnumerable<string> enumerable = Enumerable.Intersect(A, B).OrderBy(x => x);
print.WriteLine(enumerable.Count());
foreach (var intersect in enumerable)
{
print.WriteLine(intersect);
}
}
}
}