Classic example - wages (greedy) classic example - wages (greedy)

Classic example - wages (greedy)

A classic example: Treasury mustaches teacher recently considered a problem: If the amount of wages each teacher knows how many need to prepare a minimum of RMB in order in time to give every teacher wages of teachers do not give change it ?
It is assumed that teacher salaries are positive integers, unit Yuan, a total of RMB 100 yuan, 50 yuan, 10 yuan, 5 yuan, two yuan and 1 yuan six kinds.

Input

The number of input data comprising a plurality of test example, the first line of each test case is an integer n (n <100), represented by the teacher, and n is a teacher's salary.
n = 0 indicates the end of input, not treated.

Output

Each output a test case for the integer x, represents at least RMB sheets need to be prepared. Each output per line.

Sample Input

3
1 2 3
0

Sample Output

4

Solution

Greedy algorithm, at least let the bill given. First with large denomination banknotes checkout, if not, then a smaller size with a face value of paper money, and so on.
Is defined as the result mod the amount of the bill to bill denominations modular arithmetic.



#include <stdio.h>

int main()
{
    int n;
    int a[100];
    int money[6]={ 100,50,10,5,2,1 };
    int ans = 0;
    int mod,i,j=0;
    while (scanf("%d", &n) && n!=0)

    {

        for (i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        for (i = 0; i < n; i++)
        {
            mod = a[i];//初始化mod为a[i]
            while (1)
            {
                ans += mod / money[j];//对结果进行下取整
                mod = mod % money[j];//mod=余数
                j++;
                if (j == 6)
                {
                    j = 0;
                    break;
                }
            }
        }
        printf("%d\n", ans);
        ans = 0;

    }
}
  
  
Published 25 original articles · won praise 5 · Views 326

Guess you like

Origin blog.csdn.net/weixin_44602007/article/details/105152564