4358번: 생태학
프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어
www.acmicpc.net
> 의식의 흐름
해시맵 써서 정렬하고 어찌저찌,,
> 풀이
1. HashMap(key = 종 이름, value = 입력된 횟수)을 이용하여 종 이름이 몇 번 입력되었는지 저장한다.
2. 1번 과정을 입력 끝날 때까지 반복
// 입력 끝날 때까지 반복
while((type=br.readLine())!=null && !type.isEmpty()){
//...
}
3. HashMap의 키값들(종 이름)을 사전순으로 정렬한다.
4. 정렬된 순서대로 해당 종이 전체에서 몇 %를 차지하는지 출력한다.
> 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
public class Main {
public static HashMap<String,Integer> trees = new HashMap<>();
public static int totalCnt = 0;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String type = "";
while((type=br.readLine())!=null && !type.isEmpty()){
totalCnt++;
if(trees.containsKey(type)){ // 한번 입력된 종인 경우
trees.put(type, trees.get(type)+1);
}
else{ // 처음 입력된 종인 경우
trees.put(type,1);
}
}
ArrayList<String> typeNames = new ArrayList<>(trees.keySet());
Collections.sort(typeNames);
for(String typeName:typeNames){
Double typePercent = (double)(trees.get(typeName)*100)/(double)totalCnt;
bw.write(typeName+" "+String.format("%.4f",typePercent)+'\n');
}
bw.flush();
br.close();
bw.close();
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[JAVA] 백준 q14675 - 단절점과 단절선 (0) | 2023.09.19 |
---|---|
[JAVA] 백준 q7662 - 이중 우선순위 큐 (0) | 2023.09.15 |
[JAVA] 백준 q2580 - 스도쿠 (0) | 2023.08.08 |
[JAVA] 백준 q3055 - 탈출 (0) | 2023.08.08 |
[JAVA] 백준 q11003 - 최솟값 찾기 (0) | 2023.08.08 |