link
class Solution {
public:
#define LL long long
unordered_map<int,LL> memo;
int busRapidTransit(int target, int inc, int dec, vector<int>& jump, vector<int>& cost) {
int mod=1E9+7;
return dfs(target,inc,dec,jump,cost)%mod;
}
LL dfs(int u, int inc, int dec, vector<int>& jump, vector<int>& cost){
if(u==0) return 0;
if(u==1) return inc;
if(memo.find(u)!=memo.end()) return memo[u];
LL res=(LL)inc*u;
for(int i=0;i<jump.size();i++){
if(u%jump[i]==0){
res=min(res,(LL)cost[i]+dfs(u/jump[i],inc,dec,jump,cost));
}else{
if(u>jump[i]){
LL t=(LL)cost[i]+(LL)inc*(u%jump[i])+dfs(u/jump[i],inc,dec,jump,cost);
res=min(res,t);
}
LL t=(LL)cost[i]+(LL)dec*(jump[i]-u%jump[i])+dfs(u/jump[i]+1,inc,dec,jump,cost);
res=min(res,t);
}
}
return memo[u]= res;
}
};