貪心演算法 Problem F 1005 花最少(數量)的紙幣
阿新 • • 發佈:2018-12-23
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int main(){ int n; cin>>n; while(n--){ int a[5],b[5]; memset(a,0,5*sizeof(int)); memset(b,0,5*sizeof(int)); int total,total_,cnt1=0,cnt2=0; cin>>total; total_=total; for(int i=0;i<5;++i){ cin>>a[i]; b[i]=a[i]; } if(total>=100&&a[4]!=0){ //能用大額的紙幣就優先用大額。 int need; need=total/100; if(a[4]>=need){ cnt1+=need; a[4]-=need; total-=need*100; } else{ cnt1+=a[4]; total-=a[4]*100; a[4]=0; } } if(total>=50&&a[3]!=0){ int need; need=total/50; if(a[3]>=need){ cnt1+=need; a[3]-=need; total-=need*50; } else{ cnt1+=a[3]; total-=a[3]*50; a[3]=0; } } if(total>=10&&a[2]!=0){ int need; need=total/10; if(a[2]>=need){ cnt1+=need; a[2]-=need; total-=need*10; } else{ cnt1+=a[2]; total-=a[2]*10; a[2]=0; } } if(total>=5&&a[1]!=0){ int need; need=total/5; if(a[1]>=need){ cnt1+=need; a[1]-=need; total-=need*5; } else{ cnt1+=a[1]; total-=a[1]*5; a[1]=0; } } if(total>=1&&a[0]!=0){ int need; need=total; if(a[0]>=need){ cnt1+=need; a[0]-=need; total-=need*1; } else{ cnt1+=a[0]; total-=a[0]*1; a[0]=0; } } if(total!=0){ cout<<"-1 -1"<<endl;//如果求最少花多少紙幣時找不到滿足條件,則求最多花多少紙幣也一定沒有滿足條件(輸出-1 -1)。 continue;} int last; int num=b[0]+b[1]+b[2]+b[3]+b[4];//錢的總張數。 last=b[0]+b[1]*5+b[2]*10+b[3]*50+b[4]*100-total_;//買書後剩餘的錢。 if(last>=100&&b[4]!=0){ int need; need=last/100; if(b[4]>=need){ cnt2+=need; b[4]-=need; last-=need*100; } else{ cnt2+=b[4]; last-=b[4]*100; b[4]=0; } } if(last>=50&&b[3]!=0){ int need; need=last/50; if(b[3]>=need){ cnt2+=need; b[3]-=need; last-=need*50; } else{ cnt2+=b[3]; last-=b[3]*50; b[3]=0; } } if(last>=10&&b[2]!=0){ int need; need=last/10; if(b[2]>=need){ cnt2+=need; b[2]-=need; last-=need*10; } else{ cnt2+=b[2]; last-=b[2]*10; b[2]=0; } } if(last>=5&&b[1]!=0){ int need; need=last/5; if(b[1]>=need){ cnt2+=need; b[1]-=need; last-=need*5; } else{ cnt2+=b[1]; last-=b[1]*5; b[1]=0; } } if(last>=1&&b[0]!=0){ int need; need=last; if(b[0]>=need){ cnt2+=need; b[0]-=need; last-=need*1; } else{ cnt2+=b[0]; last-=b[0]*1; b[0]=0; } } cnt2=num-cnt2; cout<<cnt1<<' '<<cnt2<<endl; } return 0; }