B. Our Tanya is Crying Out Loud

题目链接:http://codeforces.com/contest/940/problem/B

B. Our Tanya is Crying Out Loud

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Right now she actually isn't. But she will be, if you don't solve this problem.

You are given integers nkA 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
Note

In the first testcase, the optimal strategy is as follows:

  • Subtract 1 from x (9 → 8) paying 3 coins.
  • Divide x by 2 (8 → 4) paying 1 coin.
  • Divide x by 2 (4 → 2) paying 1 coin.
  • Divide x by 2 (2 → 1) paying 1 coin.

The total cost is 6 coins.

In the second test case the optimal strategy is to subtract 1 from x 4 times paying 8 coins in total.


题意:给定整数n.k.a.b,规定将某数减一花费a,将某数除以k花费b,问将n变为1所需的最小花费。

题解:四个数都是2e9的范围。当n减小到小于k时,只能使用减一操作。否则就先减到距离n最近的k的倍数再除以k。注意两点,第一获取距离n最近的k的倍数的方法是n/k*k,第二在除以k的时候要判断除法花费是否比减去n-n/k要小。

给出AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,k,A,B;
ll Min(ll a,ll b)
{
	return a<b?a:b;
}
int main()
{
	cin>>n>>k>>A>>B;
	ll ans=0;
	if(k==1)
	{
		cout<<A*(n-1)<<endl;
		return 0;
	}
	while(n!=1)
	{
		if(n<k)
		{
			ans+=A*(n-1);
			break;
		}
		if(n%k!=0)
		{
			ans+=A*(n-n/k*k);
			n=n/k*k;
		}
		ans+=Min(B,A*(n-n/k));
		n/=k;
	}
	cout<<ans<<endl;
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值