ACM程式設計大賽-------- 最少錢幣數(Java程式碼)
阿新 • • 發佈:2019-02-11
【問題描述】
這是一個古老而又經典的問題。用給定的幾種錢幣湊成某個錢數,一般而言有多種方式。例如:給定了6種錢幣面值為2、5、10、20、50、100,用來湊 15元,可以用5個2元、1個5元,或者3個5元,或者1個5元、1個10元,等等。顯然,最少需要2個錢幣才能湊成15元。
你的任務就是,給定若干個互不相同的錢幣面值,程式設計計算,最少需要多少個錢幣才能湊成某個給出的錢數。
這是一個古老而又經典的問題。用給定的幾種錢幣湊成某個錢數,一般而言有多種方式。例如:給定了6種錢幣面值為2、5、10、20、50、100,用來湊 15元,可以用5個2元、1個5元,或者3個5元,或者1個5元、1個10元,等等。顯然,最少需要2個錢幣才能湊成15元。
你的任務就是,給定若干個互不相同的錢幣面值,程式設計計算,最少需要多少個錢幣才能湊成某個給出的錢數。
【要求】
【資料輸入】
輸入可以有多個測試用例。每個測試用例的第一行是待湊的錢數值M(1 <= M <= 2000,整數),接著的一行中,第一個整數K(1 <= K <= 10)表示幣種個數,隨後是K個互不相同的錢幣面值Ki(1 <= Ki <= 1000)。輸入M=0時結束。
【資料輸出】
每個測試用例輸出一行,即湊成錢數值M最少需要的錢幣個數。如果湊錢失敗,輸出“Impossible”。你可以假設,每種待湊錢幣的數量是無限多的。
【樣例輸入】
15
6 2 5 10 20 50 100
1
1 2
0
【樣例輸出】 2Impossible
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class ACM { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan=new Scanner(System.in); List<Integer> result=new ArrayList<Integer>(); int typeNum=0; int money=0; boolean isOK=true; System.out.println("請輸入一個待湊錢幣,輸入0結束"); while(isOK){ try { money=scan.nextInt(); isOK=false; } catch (Exception e) { // TODO: handle exception System.out.println("輸入有誤,請重新輸入一個正整數"); isOK=true; } } while(money!=0){ int count=0; System.out.println("請輸入貨比種類數"); isOK=true; while(isOK){ try { typeNum=scan.nextInt(); isOK=false; } catch (Exception e) { // TODO: handle exception System.out.println("輸入有誤,請重新輸入一個正整數"); isOK=true; } } int[] type=new int[typeNum]; System.out.println("請輸入貨幣面值"); for (int i = 0; i < type.length; i++) { type[i]=scan.nextInt(); } type=reverse(type); for (int i = 0; i < type.length; i++) { while(money/type[i]!=0){ money-=type[i]; count++; } } result.add(count); System.out.println("請輸入一個待湊錢幣,輸入0結束"); isOK=true; while(isOK){ try { money=scan.nextInt(); isOK=false; } catch (Exception e) { // TODO: handle exception System.out.println("輸入有誤,請重新輸入一個正整數"); isOK=true; } } } for (int i = 0; i < result.size(); i++) { if(result.get(i).intValue()==0){ System.out.println("Impossible "); }else{ System.out.println(result.get(i).intValue()); } } } public static int[] reverse(int[] arr) { int temp=0; for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if(arr[i]<arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } return arr; } }