알고리즘(백준 등) 공부/백준(자바)
백준 1431번: 시리얼 번호
posite
2026. 4. 25. 12:03
문자열들을 주어진 조건에 맞게 정렬한 결과를 나열하는 문제이다.
우선순위 큐에 길이 비교, 숫자인 자릿수의 합 비교, 사전순으로 정렬하기 작업을 순서대로 수행하는 정렬 기준을 구현해주면 된다.
PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return -1;
} else if (o1.length() > o2.length()) {
return 1;
} else {
int a = 0, b = 0;
for (int i = 0; i < o1.length(); i++) {
if (!Character.isAlphabetic(o1.charAt(i))) {
a += Integer.parseInt(o1.substring(i, i + 1));
}
if (!Character.isAlphabetic(o2.charAt(i))) {
b += Integer.parseInt(o2.substring(i, i + 1));
}
}
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return o1.compareTo(o2);
}
}
}
});
결과 코드는 다음과 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
public class 시리얼번호1431 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return -1;
} else if (o1.length() > o2.length()) {
return 1;
} else {
int a = 0, b = 0;
for (int i = 0; i < o1.length(); i++) {
if (!Character.isAlphabetic(o1.charAt(i))) {
a += Integer.parseInt(o1.substring(i, i + 1));
}
if (!Character.isAlphabetic(o2.charAt(i))) {
b += Integer.parseInt(o2.substring(i, i + 1));
}
}
if (a > b) {
return 1;
} else if (b > a) {
return -1;
} else {
return o1.compareTo(o2);
}
}
}
});
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
pq.add(br.readLine());
}
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
sb.append(pq.remove()).append('\n');
}
System.out.print(sb);
}
}