본문 바로가기
Algorithm

[백준] 10814: 나이순 정렬(Java)

by 옥돔이와 연근이 2022. 10. 3.
728x90
반응형

💡 문제보기

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;
			}

		}
	}

}
728x90