牛客网 Big Boss(完全揹包)

题目链接:Big Boss

链接:https://www.nowcoder.com/acm/contest/102/L
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld
题目描述
Many years later, Rainbow Island is in the mercy of big boss qiami. Big boss qiami is fond of number 9 because each side of the magic cube is made up of 9 small pieces and he changes the face value of circulating currency to 90,91,92,93,94 Yuan.
One day programmer Uucloud went to a shop to buy Cat food worth n Yuan. The shopkeeper NoMoreWords and Uucloud are good friends so he will give Uucloud his change. Uucloud wants to know how many bills do they need in their trade at least.
For example, if Uucloud wants to buy cat food of 8 Yuan, he will pay a 9 Yuan bill and NoMoreWords will give Uucloud 1 Yuan bill as change. Two paper money are used in this trade.

输入描述:
The first line contains an integer number T, the number of test cases.
Next T lines contains a number n(1 ≤ n ≤ 109)。
输出描述:
For each test case print the number of bills they need at least.
示例1
输入
2
14
18
输出
6
2

思路:大于6561(9^4)的部分一定是用6561来支付的,所以只用算出0-6561以内所有情况的所需要钱的最小数就行了。

我记着有一道题是给你一些秤砣,问你能不能称量出给你的斤数,因为秤砣可以两边放,所以有负数的情况,座标轴往右移就行了。和这道题是一样的。

代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
int dp[81*81*2+9];
int a[5]= {1,9,81,729,81*81};//有五种钱
void init()//完全揹包,算出所有的情况
{
    //这里因为是可以找钱的,所以可能有负数的情况
    //0-9^4-1是负数的情况,9^4是0点,9^4+1--(9^4)*2是整数的情况。
    memset(dp,inf,sizeof(dp));
    dp[81*81]=0;
    for(int i=0; i<5; i++)
    {
        for(int j=0; j+a[i]<=81*81*2; j++)//加上这五个数的情况,
        {
            if(dp[j]!=inf&&dp[j+a[i]]>dp[j]+1)
                dp[j+a[i]]=dp[j]+1;
        }
        for(int j=81*81*2; j-a[i]>=0; j--)//减去这五个数的情况。
        {
            if(dp[j]!=inf&&dp[j-a[i]]>dp[j]+1)
                dp[j-a[i]]=dp[j]+1;
        }
    }
}
int main()
{
    init();
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int ans=n/(81*81);//超出9^4的部分
        n%=(81*81);//剩余的部分
        printf("%d\n",ans+dp[n+81*81]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章