A - Pay to Win(记忆化搜索)

A - Pay to Win(记忆化搜索)

传送门

思路:将问题倒着考虑,从 n n 到0. 显然每一步有4种方式。

但是对于 k = 2 , 3 , 5 k=2,3,5 要满足 2 n , 3 n , 5 n 2|n,3|n,5|n 才行。所以这三种方式分别产生两种情况,

向上取整到达和向下取整到达。

[ n / 2 , ( n + 1 ) / 2 ] , [ n / 3 , ( n + 1 ) / 3 ] , [ n / 5 , ( n + 4 ) / 5 ] [n/2,(n+1)/2],[n/3,(n+1)/3],[n/5,(n+4)/5] .

因此可以进行 d f s dfs ,因为数据较大,所以应该采用 记忆化搜索,用 m a p map 记录一下当前 n n 的最小值。

时间复杂度: c n t ( n 2 a × 3 b × 5 c ) cnt(\dfrac{n}{2^a\times 3^b\times 5^c}) (状态数)

AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+5;
#define mst(a) memset(a,0,sizeof a)
ll a,b,c,d,n;
unordered_map<ll,ll>mp; 
ll dfs(ll n){
	if(!n) return 0;
	if(n==1) return d;
	if(mp[n]) return mp[n];
	ll res=1e18;
	if(n<res/d) res=n*d;
	res=min(res,a+n%2*d+dfs(n/2));
	res=min(res,a+(2-n%2)*d+dfs((n+1)/2));
	res=min(res,b+n%3*d+dfs(n/3));
	res=min(res,b+(3-n%3)*d+dfs((n+2)/3));
	res=min(res,c+n%5*d+dfs(n/5));
	res=min(res,c+(5-n%5)*d+dfs((n+4)/5));
	mp[n]=res;
	return res;
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		mp.clear();
	scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&d);
	  printf("%lld\n",dfs(n));
	 }
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/106311564