Right now she actually isn't. But she will be, if you don't solve this problem.
You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations:
- Subtract 1 from x. This operation costs you A coins.
- Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·109).
The second line contains a single integer k (1 ≤ k ≤ 2·109).
The third line contains a single integer A (1 ≤ A ≤ 2·109).
The fourth line contains a single integer B (1 ≤ B ≤ 2·109).
Output
Output a single integer — the minimum amount of coins you have to pay to make x equal to 1.
Examples
Input
Copy
9 2 3 1
Output
6
Input
Copy
5 5 2 20
Output
8
Input
Copy
19 3 4 2
Output
12
当时实在是不知道应该怎样最快的找到 距离n最近的k的倍数,简直菜死了
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
const int maxn=1010;
/*
暴力都不会QAQ
*/
int main()
{
ll ans=0;
ll n,k,a,b;
scanf("%lld %lld %lld %lld",&n,&k,&a,&b);
if(k==1) {
printf("%lld\n",(n-1)*a);
return 0;
}
while(n>1) {
if(n<k) {
ans+=(n-1)*a;
n=1;
break;
}
ll t=n/k;//计算n与k的倍数离的最近的点,/的特性(当时我就想--,这样的话,确实是太麻烦了)
if(n%k) {//结果变成t,只不过还是两条路
ll r=n-t*k;
ans+=min(r*a+b,(n-t)*a);//一除一减也可能是不如直接减的花费少
} else
ans+=min((n-t)*a,b);//也是两条路
n/=k;
}
printf("%lld\n",ans);
return 0;
}