https://www.acmicpc.net/problem/4358
사용 알고리즘
- 맵
- 문자열
풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Map<String, Integer> map = new HashMap<>();
String input;
int total = 0;
while((input = br.readLine()) != null && !input.isEmpty()) {
map.put(input, map.getOrDefault(input, 0) + 1);
total++;
}
List<String> list = new ArrayList<>(map.keySet());
Collections.sort(list);
for (String s : list) {
double res = (double) map.get(s) / total * 100;
String portion = String.format("%.4f", res);
System.out.println(s + " " + portion);
}
}
}
회고
이전까지 항상 n까지의 입력값을 받다가, 그런 조건이 없는 문제를 오랜만에 풀어서 입력값에 시간이 좀 걸렸다.
String input;
while((input = br.readLine()) != null && !input.isEmpty()) {
...
}
이런식으로 로직을 짜면 공백을 입력받기 전까지 입력값을 받는다.
그뒤로, String 형태의 리스트를 만들어서 해쉬맵의 keySet을 저장하고, 알파벳 순서대로 정렬해주면 된다.
문제에서 요구하는 조건이 소숫점 4째자리까지 반올림을 해주는 것인데, String,format("%.4f" ..)를 사용하면 답을 도출할 수 있다.
'Algorithm > 백준' 카테고리의 다른 글
[그래프] 위상정렬 (0) | 2024.07.29 |
---|---|
[백준] Silver I. 절댓값 힙 (0) | 2024.07.23 |
[백준] Gold IV. 부분 합 (0) | 2024.07.21 |
[백준] Gold V. 두 용액 (0) | 2024.07.20 |
[백준] Gold V. 수 고르기 (0) | 2024.07.20 |