일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 이펙티브 자바
- UML
- 포트앤어댑터 아키텍처
- 알고리즘
- disjoint set
- dfs
- series
- 문자열
- dataframe
- java
- BFS
- pandas
- 위상정렬
- docker
- spring security
- ddd
- 자바
- Redis
- 비트마스크
- 데이터 flow
- DP
- equals
- 백준
- 헥사고날 아키텍처
- 세그먼트 트리
- springboot
- 파이썬
- JPA
- 스프링
- 다익스트라
Archives
- Today
- Total
코딩못하는사람
1339 단어수학 본문
1339번: 단어 수학
첫째 줄에 단어의 개수 N(1 ≤ N ≤ 10)이 주어진다. 둘째 줄부터 N개의 줄에 단어가 한 줄에 하나씩 주어진다. 단어는 알파벳 대문자로만 이루어져있다. 모든 단어에 포함되어 있는 알파벳은 최대
www.acmicpc.net
1.접근
각 알파벳에 자리수를 곱해서 가장 큰 값부터 9를 할당해서 문제를 푸는 그리디 문제이다
2.풀이
알파벳을 한줄 씩 입력받을 때 마다 자릿 수를 곱해서 Map에 저장한다.
예를들면 ABC는 A에 100, B에 10, C에 1을 더하는 것이다.
이렇게 map을 만들고 value값이 가장 큰 순으로 정렬해서 9부터 1씩 줄여가며 곱해서 답을 출력한다.
3.코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class 단어수학_1339 { | |
public static void main(String[] args) { | |
Scanner sc=new Scanner(System.in); | |
int n=sc.nextInt(); | |
int ans=0; | |
HashMap<Integer,Integer> M=new HashMap<>(); | |
for (int i=0;i<n;i++){ | |
String temp=sc.next(); | |
int l=temp.length(); | |
for (int j=0;j<l;j++){ | |
if (M.containsKey(temp.charAt(j)-'A')){ | |
M.put(temp.charAt(j)-'A',M.get(temp.charAt(j)-'A')+(int)Math.pow(10,l-j-1)); | |
}else { | |
M.put(temp.charAt(j) - 'A', (int) Math.pow(10, l - j - 1)); | |
} | |
} | |
} | |
ArrayList<Integer> arr=new ArrayList<>(M.keySet()); | |
Collections.sort(arr, new Comparator<Integer>() { | |
@Override | |
public int compare(Integer o1, Integer o2) { | |
return M.get(o2).compareTo(M.get(o1)); | |
} | |
}); | |
for (int i=0;i<arr.size();i++){ | |
ans+=(9-i)*M.get(arr.get(i)); | |
} | |
System.out.println(ans); | |
} | |
} |
4.배운점
(1)Map에서 value값에 따라 정렬하는 방법
기존 정렬 방식과 다른 value값을 통한 정렬이므로 Map의 keySet을 ArrayList로 만들고
그 ArrayList를 새로운 Comparator을 선언하여 compare메서드를 override해주었다.
value값이므로 M.get(o1).compareTo(M.get(o2))로 정의하면 오름차순
M.get(o2).compareTo(M.get(o1))로 정의하면 내림차순이 된다.(이 문제에서는 내림차순)
(1)Math.pow()를 통해서 거듭제곱을 나타낼 수 있다.
pow(2,5)=32.0 ==>2^5 (double 형으로 나온다)
'백준 문제풀이(JAVA,Python)' 카테고리의 다른 글
22116 창영이와 퇴근[priority queue,Binary Search] (0) | 2021.08.18 |
---|---|
19584 난개발 (누적합,TreeSet) (0) | 2021.06.30 |
파이썬 문자열 문제 (find,in,KMP알고리즘) ,7575 바이러스(백준) (0) | 2020.11.27 |
1062 가르침 (비트마스킹) (0) | 2020.11.23 |
12899 데이터 구조 (0) | 2020.11.10 |