牛客练习赛87 牛老板 (记忆化搜索)

原题链接

题意:

牛老板(牛牛)是一个土豪,他有无穷数量的纸币,但他的纸币面值很奇怪:
牛老板纸币的面值要么为 6 i {6^i} 6i要么为 9 i {9^i} 9i,其中i∈[−∞,∞]且i为整数。
牛老板买了一架私人飞机售卖价格为X,牛老板希望在不找零的情况下用尽可能少的纸币付钱,请你帮牛老板计算至少需要多少张纸币。
X < = 1 e 12 X<=1e12 X<=1e12

思路:

最开始的思路是将 x x x转为九进制,状压枚举每一个选的位置,表示这部分用 9 9 9的纸币;剩下的部分用 6 6 6的纸币,取最小值就好。因为 x x x的十进制为 12 12 12位,九进制也就为 15 位 15位 15以内,时间复杂度是过得去的。
但是这样有一个问题就是,没有包含所有的情况,比如这个数可以拆出来 3 3 3 9 6 9^6 96,不一定用 3 3 3 9 6 9^6 96的纸币是最优的。
采用记忆化搜索的方式, d p [ i ] dp[i] dp[i]表示价格为 i i i最少要用的纸币数量。每次从小于 i i i的最大数开始计算。

代码:

#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read(){ll x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}

inline void write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)

ll ksm(ll a, ll b,ll mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}

const int maxn=1e6+7;

vector<ll>v1,v2;
map<ll,int>dp;
void init(){
    ll x=6;
    while(x<=1e12) v1.push_back(x),x*=6;
    x=9;
    while(x<=1e12) v2.push_back(x),x*=9;
}

int dfs(ll n){
    if(!n||dp[n]) return dp[n];
    dp[n]=0x3f3f3f3f;
    int pos=upper_bound(v1.begin(), v1.end(),n)-v1.begin()-1;
    if(pos>=0) dp[n]=min(dp[n],dfs(n-v1[pos])+1);
    pos=upper_bound(v2.begin(),v2.end(),n)-v2.begin()-1;
    if(pos>=0) dp[n]=min(dp[n],dfs(n-v2[pos])+1);
    if(n<=5) dp[n]=min(dp[n],dfs(n-1)+1);
    return dp[n];
}

int main(){
	init();
    int _=read;
    while(_--){
        ll n=read;
        cout<<dfs(n)<<endl;
    }
	return 0;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆沙睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值