Today's special moments become memories of tomorrow.

BOJ

[백준 4358번] 생태학 (java)

lotus lee 2021. 3. 2. 18:10

www.acmicpc.net/problem/4358

 

4358번: 생태학

프로그램은 여러 줄로 이루어져 있으며, 한 줄에 하나의 나무 종 이름이 주어진다. 어떤 종 이름도 30글자를 넘지 않으며, 입력에는 최대 10,000개의 종이 주어지고 최대 1,000,000그루의 나무가 주어

www.acmicpc.net

 

HashMap을 사용하여서 쉽게 풀었다.

맵의 Key에는 종 이름을, Value에는 종의 개수를 새어서 증가시켜준다.

 

소스코드 : 

import java.io.*;
import java.util.*;
public class Main {
static int total;
static HashMap<String, Integer> map = new HashMap<>();
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 word = "";
while ((word = br.readLine()) != null) {
map.computeIfAbsent(word, key -> new Integer(0));
map.put(word, map.get(word) + 1);
total++;
}
List<String> list = new ArrayList<>();
for (String s : map.keySet())
list.add(s);
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
String name = list.get(i);
int cnt = map.get(name);
bw.write(name + " " + String.format("%.4f", (double) cnt * 100 / (double) total) + "\n");
}
bw.flush();
}
}
view raw 4358.java hosted with ❤ by GitHub

 

'BOJ' 카테고리의 다른 글

[백준 2467번] 용액 (java)  (0) 2021.03.03
[백준 2660번] 회장뽑기 (java)  (0) 2021.03.02
[백준 2343번] 기타 레슨 (java)  (0) 2021.03.01
[백준 6236번] 용돈 관리 (java)  (0) 2021.03.01
[백준 5052번] 전화번호 목록 (java)  (0) 2021.02.27