본문 바로가기
알고리즘

[백준] 8979번: 올림픽 - java

by 육빔 2024. 9. 11.
728x90
반응형

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

 

간만에 백준으로 다시 넘어왔다. 한동안 프로그래머스에서 풀었는데 괜찮은 것 같았다. 그러나 푸는 맛이 없어서 다시 백준으로 풀 계획이다.

그나저나 java로 넘어온게 맞는 선택인가 고민이다. 물론 개발실력을 높일 순 있는데 내가 그냥 잘하는 파이썬을 할껄 그랬나..

 

뭐 쨋는 문제를 봐보자. 사실 이런 정렬문제는 파이썬에서 아주 쉽게.. 아니다. 이제 자바 얘기만 하자.

자바에서 푸는 방법을 모르겠어서 다른 사람들 코드를 참고했다.

 

우선 이런 다양한 조건이 있는 경우의 정렬은 compareTo를 상속해서 사용해야한다. 

 

왜? 그 이유는 뭐 단순한 숫자같은 경우는 어떤게 크고 작은게 명확할 것이다. 하지만 객체에서는 여러가지 조건을 어떤 기준으로 비교해서 정렬하는지의 기준이 있어야 한다. 한마디로 서장훈 vs 강호동 이런 비교에선 무조건 기준이 있어야 될 것이다.

 

compareTo 을 쓰기 위해서 객체에 Comparable 인터페이스를 상속 받는다. 그 이유는 상속을 받아서 추후 Collection.sort를 진행하게 되면 이 기준으로 정렬을 한 번 에 해주기 때문이다.

 

static class Nation implements Comparable<Nation> {
    private int name;
    private int gold;
    private int silver;
    private int bronze;
    private int rank;

    public Nation(int name, int gold, int silver, int bronze) {
        super();

        this.name = name;
        this.gold = gold;
        this.silver = silver;
        this.bronze = bronze;
        this.rank = 1;	
    } 

    @Override
    public int compareTo(Nation o) {

        if(this.gold == o.gold) {
            if(this.silver == o.silver) {
                return o.bronze - this.bronze;
            } else {
                return o.silver - this.silver;
            } 
        } else {
            return o.gold - this.gold;
        } 
    } 
}

 

그런다음 입력을 받은 다음 각 객체에 값을 저장해 List에 저장 후 정렬을 진행해준다음, for문으로 돌려주면서 완전히 같으면 같은 등수 아니면 i + 1의 등수를 넣어주는 식으로 작성됐다. 

 

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());

        List<Nation> medalList = new ArrayList<>();

        for(int i=1; i<=n; i++) {

            st = new StringTokenizer(br.readLine());

            int name = Integer.parseInt(st.nextToken());
            int gold = Integer.parseInt(st.nextToken());
            int silver = Integer.parseInt(st.nextToken());
            int bronze = Integer.parseInt(st.nextToken());

            Nation nation = new Nation(name, gold, silver, bronze);
            medalList.add(nation);
        } 

        Collections.sort(medalList);

        for(int i=1; i<n; i++) {

            Nation originN = medalList.get(i-1);
            Nation nextN = medalList.get(i);

            if(originN.gold == nextN.gold &&
                originN.silver == nextN.silver &&
                originN.bronze == nextN.bronze) {

                nextN.rank = originN.rank;
            } else {
                nextN.rank = i + 1;
            } 

        }

        medalList.stream().
            filter(t -> t.name == k).
            map(t -> t.rank).
            forEach(System.out::println);
    }

 

완성

728x90
반응형