uva 166 Making Change

博主有一个通熟易懂的方法解这道题,希望大家喜欢,背包简化,不用数组标记也可以做

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;

int coin[6] = {1,2,4,10,20,40};
int num[6];

int store(int n)
{
    int ans = 0;
    for(int i = 5; i >= 0; i--)
    {
        ans += n/coin[i];
        n = n - n/coin[i] * coin[i];
        if(n == 0)
            return ans;
    }
    return ans;

}

int buyer(int n)
{
    int ans = 0;
    for(int i = 5; i >= 0; i--)
    {
       int temp = min(num[i],n/coin[i]);
       ans += temp;
       n = n - temp * coin[i];
       if(n == 0)
        return ans;
    }
    return 10000;

}

int main()
{
    double n;
    int m;
    while(1)
    {
        m = 0;
        for(int i =0; i < 6; i++)
        {
            scanf("%d",&num[i]);
            m += num[i]*coin[i];
        }
        if(num[0] != 0 || num[1] != 0 || num[2] != 0 || num[3] != 0 || num[4] != 0 || num[5] != 0 )
        {
            scanf("%lf",&n);
            int t = (int)(n * 20 + 0.5);
            int Min = 10000;
            for(int i = 0; t + i <= m; i ++ )
            {
                int temp = buyer(t + i) + store(i);
                Min = min(Min,temp);
            }
           printf("%3d\n",Min);

        }
        else
            break;
    }

return 0;
}



你可能感兴趣的:(uva 166 Making Change)