익숙한 문제이다. HashMap<String, String[]>을 써서 그룹명을 key로 가지고 멤버를 value로 가지게 한 후, 문제 유형에 따라 처리하면 된다.
우선 데이터를 입력받는다.
Scanner scanner = new Scanner(System.in);
int groupNum = scanner.nextInt();
int quizNum = scanner.nextInt();
HashMap<String, String[]> glist = new HashMap<>();
String groupName, problem;
int groupSize;
for(int i = 0; i<groupNum; i++)
{
groupName = scanner.next();
groupSize = scanner.nextInt();
String[] member = new String[groupSize];
for(int j = 0; j<groupSize; j++)
{
member[j] = scanner.next();
}
Arrays.sort(member);
glist.put(groupName, member);
}
멤버를 사전 순으로 출력해야 하므로 Arrays.sort 함수로 멤버명을 정렬해야 한다.
다음으로 문제 유형에 따라 정답을 출력하면 된다.
1. 문제 유형이 해당 그룹의 멤버를 출력하는 것이면
HashMap에서 get을 한 후 얻은 String 배열을 전부 출력하면 된다.
2. 문제 유형이 해당 멤버를 포함하는 그룹명을 출력하는 것이면
keyset을 가져와 순회하면서 key로 get한 String 배열에 해당 멤버가 있으면 key를 출력하면 된다.
int quizType;
boolean solved;
for(int i = 0; i<quizNum; i++)
{
solved = false;
problem = scanner.next();
quizType = scanner.nextInt();
if(quizType == 1)
{
for(String s : glist.keySet())
{
if(solved)
{
break;
}
String[] list = glist.get(s);
for(int j = 0; j<list.length; j++)
{
if(list[j].equals(problem))
{
System.out.println(s);
solved = true;
break;
}
}
}
}
else
{
String[] list = glist.get(problem);
for(int j = 0; j<list.length; j++)
{
System.out.println(list[j]);
}
}
}
결과 코드
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int groupNum = scanner.nextInt();
int quizNum = scanner.nextInt();
HashMap<String, String[]> glist = new HashMap<>();
String groupName, problem;
int groupSize;
for(int i = 0; i<groupNum; i++)
{
groupName = scanner.next();
groupSize = scanner.nextInt();
String[] member = new String[groupSize];
for(int j = 0; j<groupSize; j++)
{
member[j] = scanner.next();
}
Arrays.sort(member);
glist.put(groupName, member);
}
int quizType;
boolean solved;
for(int i = 0; i<quizNum; i++)
{
solved = false;
problem = scanner.next();
quizType = scanner.nextInt();
if(quizType == 1)
{
for(String s : glist.keySet())
{
if(solved)
{
break;
}
String[] list = glist.get(s);
for(int j = 0; j<list.length; j++)
{
if(list[j].equals(problem))
{
System.out.println(s);
solved = true;
break;
}
}
}
}
else
{
String[] list = glist.get(problem);
for(int j = 0; j<list.length; j++)
{
System.out.println(list[j]);
}
}
}
}
}
'백준' 카테고리의 다른 글
13414번: 수강신청(Java) (0) | 2023.03.02 |
---|---|
1417번: 국회의원 선거(Java) (1) | 2023.03.02 |
9935번:문자열 폭발(Java) (0) | 2023.02.24 |
5052번:전화번호 목록(Java) (1) | 2023.02.24 |
5430번:AC(Java) (1) | 2023.02.24 |