[백준] PS/Java [실랜디]

[백준 1713] 후보 추천 - JAVA

SH3542 2025. 3. 5. 19:53

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

 

 

list를 쓰며 매 순간 정렬해도 널널하다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

class Main {

  static class P {

    int num, order, rank;

    P(int num, int order, int rank) {
      this.num = num;
      this.order = order;
      this.rank = rank;
    }
  }

  public static void main(String[] args) throws IOException {

    Comparator<P> comp = Comparator.comparing((P p) -> p.rank).thenComparing(p -> p.order);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());
    int M = Integer.parseInt(br.readLine());
    StringTokenizer st = new StringTokenizer(br.readLine());

    List<P> l = new ArrayList<>();
    Set<Integer> s = new HashSet<>();

    for (int i = 0; i < M; i++) {

      int num = Integer.parseInt(st.nextToken());
      l.sort(comp);

      // 사진틀에 없으면
      if (!s.contains(num)) {

        // 사진틀이 꽉찼으면
        if (l.size() == N) {
          s.remove(l.remove(0).num);
        }

        l.add(new P(num, i, 1));
        s.add(num);
      } else {

        for (P p : l) {
          if (p.num == num) {
            p.rank++;
            break;
          }
        }
      }
    }

    StringBuilder sb = new StringBuilder();
    l.stream().map(p -> p.num).sorted().forEach(num -> sb.append(num).append(' '));
    System.out.println(sb);
  }
}