[백준][1713번:후보 추천하기]

호준·2022년 1월 18일
0

Algorithm

목록 보기
16/111
post-thumbnail

문제

문제링크

월드초등학교 학생회장 후보는 일정 기간 동안 전체 학생의 추천에 의하여 정해진 수만큼 선정된다. 그래서 학교 홈페이지에 추천받은 학생의 사진을 게시할 수 있는 사진틀을 후보의 수만큼 만들었다. 추천받은 학생의 사진을 사진틀에 게시하고 추천받은 횟수를 표시하는 규칙은 다음과 같다.
학생들이 추천을 시작하기 전에 모든 사진틀은 비어있다.
어떤 학생이 특정 학생을 추천하면, 추천받은 학생의 사진이 반드시 사진틀에 게시되어야 한다.
비어있는 사진틀이 없는 경우에는 현재까지 추천 받은 횟수가 가장 적은 학생의 사진을 삭제하고, 그 자리에 새롭게 추천받은 학생의 사진을 게시한다. 이때, 현재까지 추천 받은 횟수가 가장 적은 학생이 두 명 이상일 경우에는 그러한 학생들 중 게시된 지 가장 오래된 사진을 삭제한다.
현재 사진이 게시된 학생이 다른 학생의 추천을 받은 경우에는 추천받은 횟수만 증가시킨다.
사진틀에 게시된 사진이 삭제되는 경우에는 해당 학생이 추천받은 횟수는 0으로 바뀐다.
후보의 수 즉, 사진틀의 개수와 전체 학생의 추천 결과가 추천받은 순서대로 주어졌을 때, 최종 후보가 누구인지 결정하는 프로그램을 작성하시오.

입력

첫째 줄에는 사진틀의 개수 N이 주어진다. (1 ≤ N ≤ 20) 둘째 줄에는 전체 학생의 총 추천 횟수가 주어지고, 셋째 줄에는 추천받은 학생을 나타내는 번호가 빈 칸을 사이에 두고 추천받은 순서대로 주어진다. 총 추천 횟수는 1,000번 이하이며 학생을 나타내는 번호는 1부터 100까지의 자연수이다.

출력

사진틀에 사진이 게재된 최종 후보의 학생 번호를 증가하는 순서대로 출력한다.

코드

package DAY01.P1713;

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

public class Main {
    static int N, K;
    static Student[] students;

    static class Student implements Comparable<Student>{
        int num; // 자기 번호
        int count; // 투표받은 수
        int time; // 들어온 시간
        boolean isIn;

        public Student(int num, int count, int time, boolean isIn) {
            this.num = num;
            this.count = count;
            this.time = time;
            this.isIn = isIn;
        }
        @Override
        public int compareTo(Student o) {
            int comp1 = Integer.compare(count, o.count); //오름차순
            if(comp1 == 0){
                return Integer.compare(time, o.time); // 오름차순
            }else{
                return comp1;
            }
        }
    }
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        N = sc.nextInt();
        K = sc.nextInt();

        students = new Student[101]; // 0~100 인덱스 사용가능

        List<Student> list = new ArrayList<>();
        for (int k = 0; k < K; k++) {
            int num = sc.nextInt();
            if (students[num] == null) {
                students[num] = new Student(num, 0, 0, false);
            }
            // 사진판에 있는 경우 -> count++
            if (students[num].isIn == true) {
                students[num].count++;
            } else {// 사진판에 없는 경우 -> (자리가 없는 경우 하나 골라서, 제거 후) 새 후보 추가가
                if(list.size() == N){
                    Collections.sort(list);
                    Student student = list.remove(0);
                    student.isIn = false;
                }
                students[num].count = 1;
                students[num].isIn = true;
                students[num].time = k;
                list.add(students[num]);
            }
        }
        Collections.sort(list, Comparator.comparingInt(o -> o.num));
//        Collections.sort(list, (o1,o2) -> Integer.compare(o1.num, o2.num));

//        Collections.sort(list, new Comparator<Student>(){
//           @Override
//           public int compare(Student o1, Student o2){
//               return Integer.compare(o1.num, o2.num);
//           }
//        });
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i).num + " ");
        }
    }
}

※알고 넘어가지

정렬 방법 1

Comparator.comparingInt(o -> o.num));

Comparator안에 있는 int를 비교하는 comparingInt 함수이다.
타입에 따라서 comparingLong, comparingDouble도 가능하다.

정렬 방법 2

Collections.sort(list, (o1,o2) -> Integer.compare(o1.num, o2.num));

람다식으로 Integer.compare(o1.num, o2.num) Integer타입을 비교한다.

정렬 방법 3

Collections.sort(list, new Comparator<Student>(){
	@Override
	public int compare(Student o1, Student o2){
		return Integer.compare(o1.num, o2.num);
	}
});

@Override를 통해서 compare함수를 구현하여 정렬하는 방식이다.

정렬 방법 4

static class Student implements Comparable<Student>{
        int num; // 자기 번호
        int count; // 투표받은 수
        int time; // 들어온 시간
        boolean isIn;
		.
        	.
        	.
        @Override
        public int compareTo(Student o) {
            int comp1 = Integer.compare(count, o.count); //오름차순
            if(comp1 == 0){
                return Integer.compare(time, o.time); // 오름차순
            }else{
                return comp1;
            }
        }
    }

호출할 때 기본적으로 Collections.sort()를 하면 오름차순이지만 특정값에 의해 정렬를 하고 싶을 때 객체에 implements Comparable< Student > 통해 @Overide를 하여 함수 cmpareTo를 수정하여 정렬하는 방법.

위 정렬 방법들은 성능차이가 크게 나지 않는다. 자신이 편한 방법으로 쓰면 된다.

profile
도전하지 않는 사람은 실패도 성공도 없다

0개의 댓글