알고리즘/문제풀이 - 백준온라인저지

[BOJ 그리디] 동전 0 11047.JAVA

나규태 2021. 6. 25. 00:04
문제 링크 : https://www.acmicpc.net/problem/11047
문제 등급 : Silver II
 

11047번: 동전 0

첫째 줄에 N과 K가 주어진다. (1 ≤ N ≤ 10, 1 ≤ K ≤ 100,000,000) 둘째 줄부터 N개의 줄에 동전의 가치 Ai가 오름차순으로 주어진다. (1 ≤ Ai ≤ 1,000,000, A1 = 1, i ≥ 2인 경우에 Ai는 Ai-1의 배수)

www.acmicpc.net

문제 해결 로직

  1. 동전의 종류를 내림차순으로 정렬한다.
  2. 동전을 내림차순으로 하나씩 총금액보다 작은지 비교한다.
  3. 총금액보다 적은 금액으로 몇 번 나눌 수 있는지 계산한다.
  4. 나눈 개수를 Count하고 개수 * 금액을 총금액에서 뺀다.
  5. 2~4번을 반복하여 필요한 동전의 수를 구한다.

 

아래와 같이 소스를 공유합니다.

public class 동전0 {
    public static List<Integer> coins = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] commends = br.readLine().split(" ");

        int n = Integer.parseInt(commends[0]);
        int tot = Integer.parseInt(commends[1]);

        for(int i = 0; i < n; i++) {
            int coin = Integer.parseInt(br.readLine());
            coins.add(coin);
        }

        coins.sort(Collections.reverseOrder());

        int cnt = 0;

        for(int i = 0; i < coins.size(); i++) {
            int unit = coins.get(i);

            if(unit <= tot) {
                int div = tot/unit;
                cnt += div;
                tot = tot - (div * unit);
            }
        }

        System.out.println(cnt);
    }
}