Codeforces Round #466 (Div. 2) B. Our Tanya is Crying Out Loud

本文介绍了一个算法问题,目标是最小化将一个整数n通过特定操作转换为1所需的代价。两种操作包括减1和整除,每种操作都有不同的成本。文章提供了完整的代码实现,并解释了如何采用贪心策略来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 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

题意:给你一个n,让你把n变成1,每次有两种操作:减一花费A,除以k花费B(整除的前提下),问你最小花费。

思路:简单贪心,当不能整除时变成整除,此时只能减。当整除时,判断除的花费和减的花费,注意特判k==1的情况,防止死循环,因为这个TLE了一发。。。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,k,a,b,ans;
int main()
{
    while(~scanf("%lld%lld%lld%lld",&n,&k,&a,&b))
    {
        if(k>n||k==1){printf("%lld\n",a*(n-1));continue;}
        ans=0;
        while(1)
        {
            if(n%k!=0)     //不能整除只能减法,减到整除为止
            {
                ans+=a*(n%k);
                n=n-(n%k);
            }
            if(n<k)   //此时只能减法,除法永远用不到,直接求解答案
            {
                ans+=a*(n-1);
                break;
            }
            if(n==1)break;
            ans+=min(a*(n-n/k),b);  //减法和除法取最小花费
            n/=k;
            if(n==1)break;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值