硬币问题(贪心)

这样求整的算法真是简洁,因为硬币值最后是1,所以任意余数都能整除掉。如果换成其他问题,末尾不是1空怕就不行了。

 

/*
问题描述:
硬币问题
有1元、5元、10元、50元、100元、500元的硬币,用最少的硬币数来支付A元。
*/
#include<iostream>
using namespace std;

const int v[6] = {1, 5, 10, 50, 100, 500};

int c[6];//输入硬币个数
int A;

void solve(){
    int ans = 0;

    for(int i = 5; i >=0; i--){
        int t = min(A / v[i], c[i]);
        A -= t * v[i];
        ans += t;
    }

    cout<<ans<<endl;
}

 

posted @ 2013-11-17 23:03  偶尔会寂寞  阅读(214)  评论(0编辑  收藏  举报