π [λ°±μ€μκ³ λ¦¬μ¦ νμ΄] Q.1339 λ¨μ΄ μν νμ΄
π λ¬Έμ
https://www.acmicpc.net/problem/1339
λ―Όμμ΄λ μννμμμ λ¨μ΄ μν λ¬Έμ λ₯Ό νΈλ μμ λ₯Ό λ°μλ€.
λ¨μ΄ μν λ¬Έμ λ Nκ°μ λ¨μ΄λ‘ μ΄λ£¨μ΄μ Έ μμΌλ©°, κ° λ¨μ΄λ μνλ²³ λλ¬Έμλ‘λ§ μ΄λ£¨μ΄μ Έ μλ€.
μ΄λ, κ° μνλ²³ λλ¬Έμλ₯Ό 0λΆν° 9κΉμ§μ μ«μ μ€ νλλ‘ λ°κΏμ Nκ°μ μλ₯Ό ν©νλ λ¬Έμ μ΄λ€.
κ°μ μνλ²³μ κ°μ μ«μλ‘ λ°κΏμΌ νλ©°, λ κ° μ΄μμ μνλ²³μ΄ κ°μ μ«μλ‘ λ°λμ΄μ§λ©΄ μ λλ€.
μλ₯Ό λ€μ΄, GCF + ACDEBλ₯Ό κ³μ°νλ€κ³ ν λ, A = 9, B = 4, C = 8, D = 6, E = 5, F = 3, G = 7λ‘ κ²°μ νλ€λ©΄,
λ μμ ν©μ 99437μ΄ λμ΄μ μ΅λκ° λ κ²μ΄λ€.
Nκ°μ λ¨μ΄κ° μ£Όμ΄μ‘μ λ, κ·Έ μμ ν©μ μ΅λλ‘ λ§λλ νλ‘κ·Έλ¨μ μμ±νμμ€.
π μ κ·Όλ²
λ¨μ΄ μν λ¬Έμ μ λλ€.
κ° μνλ²³λ§λ€ μ€λ³΅λμ§ μκ² 1~9 μ μ«μκ° μ£Όμ΄μ ΈμΌνκ³
λ¨μ΄λ€μ ν©μ΄ μ΅λκ° λλλ‘ ν΄μΌν©λλ€.
κ° μνλ²³μ΄ μλ μλ¦Ώμμ κ°μ λ ν΄
κ°μ₯ ν°κ°μ μνλ²³λΆν°
ν° μλ₯Ό λμ ν΄μ£Όλ©΄ ν μκ° μμ΅λλ€.
ex) ABA
A= 10^2+10^0
B= 10^1
= Aλ 101 μ΄κ³ Bλ 10 μΌλ‘
A λ 9 B λ 8μ λμ
ν΄μ£Όλ©΄ μ΅λκ°μ΄ λμ΅λλ€.
ex) ABACB , BDAAC
A = 10^4 + 10^2 + 10^2 + 10^1 = 10210 =>8 λμ
B = 10^3 + 10^0 + 10^4 = 11001 =>9 λμ
C = 10^1 + 10^0 = 11 =>6 λμ
D = 10^3 = 1000 =>7 λμ
89869 + 97866 = 187,755 κ°
μ΅λκ°μ
λλ€.
μνλ²³μ΄ μμΉν κ° μ리μ μλ₯Ό mapμ μ΄μ©ν΄
λ£μ΄μ£Όμκ³
mapμ value
κ° μνλ²³λ§λ€μ ν©μ κΈ°μ€μΌλ‘ μ λ ¬νμ¬
ν° κ°λΆν° μ«μλ₯Ό λμ ν΄μ£Όμμ΅λλ€.
π» μ½λ
package problem.greedy;
import java.io.*;
import java.util.*;
public class Main_1339 {
static int N;
static String words[];
static class ValueComparator implements Comparator<Character> {
Map<Character, Integer> base;
public ValueComparator(Map<Character, Integer> base) {
this.base = base;
}
public int compare(Character a, Character b) {
if (base.get(a) >= base.get(b)) { //λ°λλ‘ νλ©΄ μ€λ¦μ°¨μ <=
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
public static void main(String[] args) throws IOException {
Map<Character,Integer> map = new HashMap<>();
ValueComparator valueComparator = new ValueComparator(map);
TreeMap<Character,Integer> sortedMap = new TreeMap<>(valueComparator);
input();
for(int i=0; i<N; i++){
String word = words[i];
for(int j=0; j<word.length(); j++){
char c = word.charAt(j);
int num = (int) Math.pow(10 ,word.length()-j-1);
if(map.containsKey(c) ){
int temp = map.get(c);
map.put(c,num+temp);
}
else{
map.put(c,num);
}
}
}
sortedMap.putAll(map);
int answer = 0;
int num = 9;
for (Map.Entry<Character,Integer> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey()+" : "+map.get(entry.getKey()));
int value = map.get(entry.getKey());
answer += (value*num--);
}
System.out.println(answer);
}
public static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
words = new String[N];
for(int i=0; i<N; i++){
words[i] = br.readLine();
}
br.close();
}
}