알고리즘/구현

[BOJ] 백준 2535 - 아시아 정보올림피아드 풀이

송승현(SSH) 2022. 9. 6. 23:28

1. 문제

https://www.acmicpc.net/problem/2535

 

2535번: 아시아 정보올림피아드

첫 번째 줄에는 대회참가 학생 수를 나타내는 N이 주어진다. 단, 3 ≤ N ≤ 100이다. 두 번째 줄부터 N개의 줄에는 각 줄마다 한 학생의 소속 국가 번호, 학생 번호, 그리고 성적이 하나의 빈칸을 사

www.acmicpc.net

 

2. 풀이

백준 알고리즘 분류에서 구현으로 분류된 문제이다.

이번 문제에서는 입력의 가짓수가 국가 번호, 학생 번호, 점수로 3개이다. 이 풀이에서는 가짓수를 담을 static class를 하나 선언하여 데이터를 저장하였다. 입력에서 국가의 갯수를 알려주지 않았으므로, 중복된 입력을 막는 Set을 하나 선언하여 국가의 갯수를 파악했다.
그리고 점수에 따라 메달을 수여하므로 Comparator을 이용하여 리스트를 점수 내림차순으로 정렬하였다.

이제 리스트의 순서대로 국가 번호와 학생 번호를 출력하면 되는데, 반복을 돌면서 특정 국가가 몇 번 반복되었는지 필요했다.
nationCnt 배열을 선언하여 인덱스를 국가 번호로 생각하고 출력하는 학생이 어느 나라 번호인지를 카운트하고, 그 수가 2번이 넘어가지 않도록 했다.

 

3. 소스 코드

import java.io.*;
import java.util.*;

public class Main {
    static class Olympiad {
        int nation;
        int student_num;
        int score;

        public Olympiad(int nation, int student_num, int score) {
            this.nation = nation;
            this.student_num = student_num;
            this.score = score;
        }
    }

    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int N = Integer.parseInt(br.readLine());
        List<Olympiad> list = new ArrayList<>();
        Set<Integer> nationList = new LinkedHashSet<>();

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            list.add(new Olympiad(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
            nationList.add(list.get(i).nation);
        }

        Collections.sort(list, new Comparator<Olympiad>() {
            @Override
            public int compare(Olympiad o1, Olympiad o2) {
                return o2.score - o1.score;
            }
        });

        int[] nationCnt = new int[nationList.size() + 1];
        int cnt = 0;

        for (int i = 0; i < list.size(); i++) {
            if (nationCnt[list.get(i).nation] != 2 && cnt != 3) {
                nationCnt[list.get(i).nation] += 1;
                bw.write(list.get(i).nation + " " + list.get(i).student_num + "\n");

                cnt += 1;
            }
        }

        bw.flush();
        bw.close();
        br.close();
    }
}