728x90
1431번: 시리얼 번호
첫째 줄에 기타의 개수 N이 주어진다. N은 50보다 작거나 같다. 둘째 줄부터 N개의 줄에 시리얼 번호가 하나씩 주어진다. 시리얼 번호의 길이는 최대 50이고, 알파벳 대문자 또는 숫자로만 이루어
www.acmicpc.net
풀이
그냥 스트링 이용해서 Comparator로 비교해주면 되겠네 ~ 싶었는데, 2번 조건이 있었다.
- A와 B의 길이가 다르면, 짧은 것이 먼저 온다.
- 만약 서로 길이가 같다면, A의 모든 자리수의 합과 B의 모든 자리수의 합을 비교해서 작은 합을 가지는 것이 먼저온다. (숫자인 것만 더한다)
- 만약 1,2번 둘 조건으로도 비교할 수 없으면, 사전순으로 비교한다. 숫자가 알파벳보다 사전순으로 작다.
2번 조건이 있어서 배열로 만들어서 [문자, 숫자인 것만 더한 값]을 이용해 비교해줬다.
전체코드
package 백준renew;
import java.io.*;
import java.util.*;
public class 실버3_1431_시리얼번호 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
PriorityQueue<String[]> pq = new PriorityQueue<>(new Comparator<>() {
public int compare(String[] o1, String[] o2) {
if(o1[0].length() < o2[0].length()) {
return -1;
}else if(o1[0].length() > o2[0].length()) {
return 1;
}else {
if(Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) {
return -1;
}else if(Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) {
return 1;
}else {
return o1[0].compareTo(o2[0]);
}
}
}
});
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
for(int tc=0; tc<N; tc++) {
String tmp = br.readLine();
int num = 0;
for(int i=0; i<tmp.length(); i++) {
if(tmp.charAt(i)<58) {
num += tmp.charAt(i)-48;
}
}
String arr[] = {tmp, num+""};
pq.offer(arr);
num = 0;
}
while(!pq.isEmpty()) {
String tmp[] = pq.poll();
sb.append(tmp[0]).append('\n');
}
bw.write(sb.toString());
bw.close();
}
}
728x90
'코딩테스트 > Algorithm' 카테고리의 다른 글
[BOJ] 1303: 전쟁 - 전투 (JAVA) (0) | 2024.04.23 |
---|---|
[BOJ] 15650: N과 M(2) (JAVA) (0) | 2024.04.21 |
[BOJ] 17390: 이건 꼭 풀어야 해! (JAVA) (1) | 2024.04.19 |
[BOJ] 15720: 카우버거 (JAVA) (1) | 2024.04.19 |
[BOJ] 1063: 킹 (JAVA) (0) | 2024.04.17 |