钱币找零问题

钱币找零问题
这个问题在我们的日常生活中就更加普遍了。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。在程序中已经事先将Value按照从小到大的顺序排好。
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. #include<algorithm>  
  3. using namespace std;  
  4. const int N=7;   
  5. int Count[N]={3,0,2,1,0,3,5};  
  6. int Value[N]={1,2,5,10,20,50,100};  
  7.     
  8. int solve(int money)   
  9. {  
  10.     int num=0;  
  11.     for(int i=N-1;i>=0;i--)   
  12.     {  
  13.         int c=min(money/Value[i],Count[i]);  
  14.         money=money-c*Value[i];  
  15.         num+=c;  
  16.     }  
  17.     if(money>0) num=-1;  
  18.     return num;  
  19. }  
  20.    
  21. int main()   
  22. {  
  23.     int money;  
  24.     cin>>money;  
  25.     int res=solve(money);  
  26.     if(res!=-1) cout<<res<<endl;  
  27.     else cout<<"NO"<<endl;  
  28. }

猜你喜欢

转载自blog.csdn.net/wys_NO1/article/details/68068422