안녕하세요.
백준 1764번 '듣보잡' 문제 풀이를 진행하도록 하겠습니다.
해당 문제는 두 그룹의 사람들 이름을 받아 중복되는 이름의 수와 그 이름을 출력하는 문제입니다.
입출력 예제는 다음과 같이 주어집니다.
입력
3 4
ohhenrie
charlie
baesangwook // 그룹 1의 끝
obama
baesangwook
ohhenrie
clinton // 그룹 2의 끝
출력
2
baesangwook
ohhenrie
저는 입력으로 들어오는 사람들을 모두 한 그룹에 넣어 그중 '중복이 아닌 이름' 들을 모두 삭제시키고, 그 안에서 또 중복제거를 한 후에 사전순으로 정렬하여 답을 출력할 예정입니다. 문제의 조건중 두 그룹에서 각각 중복되는 이름은 없다고 명시되어있기 때문입니다.
먼저, 사람 이름을 넣어줄 people 리스트를 선언합니다.
그 후, 사전순 정렬된 답을 넣어줄 answer 리스트도 선언합니다.
입력은 a,b로 받아오겠습니다. (두 그룹의 수)
List<string> people = new List<string>();
List<string> answer = new List<string>();
int[] nm = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int a = nm[0];
int b = nm[1];
for 반복문으로 사람들의 이름을 people 리스트에 더해줍니다.
for (int i = 0; i < a+b; i++)
{
string name = Console.ReadLine();
people.Add(name);
}
이제 중복이 아닌 이름들을 삭제해야합니다.
people 리스트를 이름기준인 GroupBy로 묶어줍니다. 그 후에 ToDictionary를 사용하여 {이름:등장횟수, ...} 로 정리해줍니다.
이제 answer 리스트에 people 리스트 중복제거를 마친 리스트를 저장해줍니다.
그 후에 answer 리스트를 Sort로 사전순 정렬해줍니다.
var counts = people.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
people.RemoveAll(x => counts[x] == 1);
answer = people.Distinct().ToList();
answer.Sort();
마지막으로, answer의 길이와 이름들을 출력하면 정답입니다 🥳
Console.WriteLine(answer.Count);
foreach(string n in answer)
{
Console.WriteLine(n);
}
다음은 전체코드입니다.
전체코드
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
List<string> people = new List<string>();
List<string> answer = new List<string>();
int[] nm = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
int a = nm[0];
int b = nm[1];
for (int i = 0; i < a+b; i++)
{
string name = Console.ReadLine();
people.Add(name);
}
var counts = people.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
people.RemoveAll(x => counts[x] == 1);
answer = people.Distinct().ToList();
answer.Sort();
Console.WriteLine(answer.Count);
foreach(string n in answer)
{
Console.WriteLine(n);
}
}
}'알고리즘 풀이' 카테고리의 다른 글
| [C#] 백준 1874번 풀이 (0) | 2025.10.16 |
|---|---|
| [C#] 백준 1966번 문제풀이 (0) | 2025.10.12 |
| [C#] 백준 2920번 문제풀이 (1) | 2025.08.11 |
| [C#] 백준 1018번 문제풀이 (1) | 2025.07.30 |
| [C#] 백준 7568번 문제풀이 (3) | 2025.07.29 |