牛客網 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章