SDUTOJ4339奇怪的纸币

奇怪的纸币https://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2697/pid/4339

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

  大家都知道人民币的面值有1元,2元,5元。这是因为1、2、5三个都是质数,可以合理地组合成其他数字。其中除了8和9需要3个数字才能组合成功外, 10以内的其他数字都可以由1、2、5中的1个或者2个组合。另外,人民币因为配备了10,所以10-2=8,10-1=9,这就完美解决了8和9的问题。由此一来,10以内所有的数字都在2张人民币以内就可以得到解决。

小明忽然想到1、5、7也同样都是质数,那么用这些面值的纸币组成某个数最小需要多少张纸币呢?

Input

一个数字 n(1 <= n <= 100000)

Output

一个数字,代表最少需要多少张面值 1 或 5 或 7 的纸币构成。

Sample Input

10

Sample Output

2

Hint

Source

7989

解法一:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    int dp[100001];
    for (int i = 1; i < 5; i++)
        dp[i] = i;
    dp[5] = 1;
    dp[6] = 2;
    dp[7] = 1;
    while (cin >> n)
    {
        for (int i = 8; i <= n; i++)
            dp[i] = min(min(dp[i - 1], dp[i - 5]), dp[i - 7]) + 1;
        cout << dp[n] << endl;
    }
    return 0;
}

解法二(枚举法):题解法

#include <bits/stdc++.h>
using namespace std; 
int main()
{
     int n,x,y,z,ans,m; //x,y,z分别代表1,5,7的个数
     scanf("%d",&n);
     ans = 100000;
     for(x = 0;x <= n/7;x++) //枚举所有7的个数
     {
         m = n - 7 * x;
         y = m / 5;   
         m = m % 5;
         z = m;
         if(ans > x + y + z)
         {
             ans = x + y + z;
         }
     }
     printf("%d\n",ans);
     return 0;
}

猜你喜欢

转载自blog.csdn.net/Cherishlife_/article/details/84402501