반응형
💡 문제보기
https://www.acmicpc.net/problem/10814
💡풀이방식
우선순위큐를 사용해서 풀이
나이가 동일할 때는 먼저 가입한 순으로 하기 위해 index를 부여함
@Override
public int compareTo(Node o) {
if (o.age - this.age == 0) {// 나이가 동일할 경우
// 먼저가입한 애 먼저 출력
return this.idx - o.idx;
} else {
return this.age - o.age;
}
}
💡 최종코드
package 백준;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main_10814 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue arr = new PriorityQueue<>();
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int age = Integer.parseInt(st.nextToken());
String name = st.nextToken();
arr.add(new Node(i, age, name));
}
for (int i = 0; i < N; i++) {
Node node = (Node) arr.poll();
System.out.println(node.age + " " + node.name);
}
}
static class Node implements Comparable<Node> {
int idx;
int age;
String name;
public Node(int idx, int age, String name) {
this.idx = idx;
this.age = age;
this.name = name;
}
@Override
public int compareTo(Node o) {
if (o.age - this.age == 0) {// 나이가 동일할 경우
// 먼저가입한 애 먼저 출력
return this.idx - o.idx;
} else {
return this.age - o.age;
}
}
}
}
반응형
'Algorithm' 카테고리의 다른 글
[프로그래머스] 보호소에서 중성화한 동물 (0) | 2022.10.06 |
---|---|
[백준] 2630: 색종이 만들기(분할정복) (0) | 2022.10.03 |
[백준_실패] (0) | 2022.10.02 |
[SWEA]1249: 보급로 D4(Java) (0) | 2022.10.02 |
[프로그래머스] 완주하지 못한 선수(Java) (0) | 2022.10.01 |