#include <iostream> #include<algorithm> #include<math.h> #include<stdio.h> #include<string> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int m[4]={10,5,2,1};//当前有的面值 int c[4]={1,2,3,2};//当前面值对应的有多少张 int M;//要换的钱 cin>>M;int total=M; int k=0; int count=0; bool cantChang=false; while(1) { //两种结束条件 if(total==0)//当钱被换完时候 break; if(total>0&&c[3]==0)//当要换的钱太多不能被换完的时候 { cantChang=true; break; } if(m[k]<=total)//当前面值可以换,否则去换下一个面值的 { if(c[k]>0) { total-=m[k]; count++;//记录最少几张 c[k]--; } } else k++; if(c[k]==0)//如果当前面值的钱换完了,则换下一个 k++; } if(cantChang) cout<<"要换的钱太多了,不能换"<<endl; else cout<<count<<endl; return 0; }
贪心算法——换硬币
猜你喜欢
转载自blog.csdn.net/w199753/article/details/80434763
今日推荐
周排行