B. Our Tanya is Crying Out Loud

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:

  1. Subtract 1 from x. This operation costs you A coins.
  2. Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins.
What is the minimum amount of coins you have to pay to make x equal to 1?
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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值