๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/16300)
< H to O >
๋ฌธ์ ํ์ด
HashMap์ ๊ฐ ์์์ ๊ฐ์๋ฅผ ๊ตฌํด ์ ์ฅํ๋ค. ๋ง์ฝ ์ ๋ ฅ์ด C2H6 10์ด๋ผ๋ฉด HashMap์ C: 20, H: 60์ผ๋ก ์ ์ฅํ๋ค. ๊ทธ ํ ๊ตฌํ๋ ค๋ ๋ถ์๋ ๊ฐ ์์์ ๊ฐ์๋ฅผ ๊ตฌํด ์ ์ฅํ๋ค. ๋ง์ฝ C3H8 ์ด๋ผ๋ฉด HashMap์ C: 3, H: 8๋ก ์ ์ฅํ๋ค.
C: 20, H:60์ผ๋ก ๋ง๋ค ์ ์๋ C: 3, H: 8 ๊ฐ์๋ ์ด 6๊ฐ๊ฐ ๋๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
public class _16300_ { // H to O
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
String molecule = st.nextToken();
int k = Integer.parseInt(st.nextToken());
HashMap<Character, Integer> map = new HashMap<>();
findMolecule(molecule, map, k);
molecule = bf.readLine();
HashMap<Character, Integer> map2 = new HashMap<>();
findMolecule(molecule, map2, 1);
int result = Integer.MAX_VALUE;
ArrayList<Character> list = new ArrayList<>(map2.keySet());
for (int i = 0; i < list.size(); i++) {
if (!map.containsKey(list.get(i))) {
result = 0;
break;
} else {
if (map.get(list.get(i)) / map2.get(list.get(i)) == 0) {
result = 0;
break;
}
result = Math.min(result, map.get(list.get(i)) / map2.get(list.get(i)));
}
}
System.out.println(result);
}
private static void findMolecule(String molecule, HashMap<Character, Integer> map, int k) {
char temp = ' ';
String num = "";
for (int i = 0; i < molecule.length(); i++) {
if (Character.isAlphabetic(molecule.charAt(i))) {
if (temp != ' ') {
if (num.equals("")) {
num = "1";
}
if (map.containsKey(temp)) {
map.replace(temp, map.get(temp) + (Integer.parseInt(num) * k));
} else {
map.put(temp, Integer.parseInt(num) * k);
}
}
temp = molecule.charAt(i);
num = "";
} else {
num += molecule.charAt(i);
}
}
if (num.equals("")) {
num = "1";
}
if (map.containsKey(temp)) {
map.replace(temp, map.get(temp) + (Integer.parseInt(num) * k));
} else {
map.put(temp, Integer.parseInt(num) * k);
}
}
}
๋ณ์)
molecule : ์ ๋ ฅ๋ฐ์ ๋ถ์
k : ๊ฐ์ง๊ณ ์๋ ๋ถ์ ๊ฐ์
map, map2 : ๊ฐ ๋ถ์๋ฅผ ์ด๋ฃจ๋ ์์ ๊ฐ์
result : ๋ง๋ค ์ ์๋ ๊ฐ์
list : ๋ง๋ค๋ ค๋ ๋ถ์์ ์์
Main
๊ฐ์ง๊ณ ์๋ ๋ถ์์ ๋ถ์ ๊ฐ์๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. findMolecule์ ํธ์ถํ์ฌ ๋ถ์์ ์์ ๊ฐ์๋ฅผ HashMap์ ์ ์ฅํ๋ค. ๋ง๋ค๋ ค๋ ๋ถ์๋ฅผ ์ ๋ ฅ๋ฐ์ ๋๊ฐ์ด findMolecule์ ํธ์ถํ์ฌ ๋ถ์์ ์์ ๊ฐ์๋ฅผ HashMap์ ์ ์ฅํ๋ค. ๊ฐ ์์์ ๊ฐ์๋ฅผ ๋น๊ตํ์ฌ ๋ง๋ค ์ ์๋ ์ต๋ ๊ฐ์๋ฅผ ๊ตฌํ๋ค.
findMolecule
๋ถ์๋ฅผ ํ์ํ๋ฉฐ ์ํ๋ฒณ์ผ ๋์ ์ซ์์ผ ๋๋ฅผ ๊ตฌ๋ถํ์ฌ HashMap์ ๊ฐ ์์์ ๊ฐ์๋ฅผ ์ ์ฅํ๋ค.
'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 32076_Easy as ABC (2) | 2025.07.10 |
---|---|
[Baekjoon] 3518_๊ณต๋ฐฑ์ ๋น-์นธ (1) | 2025.07.09 |
[Baekjoon] 26043_์๋น ๋ฉ๋ด (3) | 2025.07.07 |
[Baekjoon] 15323_ZigZag (1) | 2025.06.27 |
[Baekjoon] 13732_Falling Apples (2) | 2025.06.26 |