题目链接:http://codeforces.com/contest/940/problem/B
B. Our Tanya is Crying Out Loud
题意:给定整数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;
}