zoukankan      html  css  js  c++  java
  • Codeforce940B (Our Tanya is Crying Out Loud)

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

    分析:贪心。注意判断k==1的情况。

    #include<cstdio>
    using namespace std;
    int main()
    {
        long long N,k,A,B;
        scanf("%lld%lld%lld%lld",&N,&k,&A,&B);
        long long ans=0;
        if(k==1)
        {
            printf("%lld
    ",A*(N-1));
            return 0;
        }
        while(N>=k)
        {
            if(N%k==0)
            {
                long long next=N/k;
                if((N-next)*A>B) ans+=B;
                else ans+=(N-next)*A;
                N=next;
            }
            else
            {
                long long t=N/k;
                long long temp=N-t*k;
                ans+=A*temp;
                N=t*k;
            }
        }
        if(N!=1)//N<k时 
        ans+=A*(N-1);
        printf("%lld
    ",ans);
        return 0;
    }
    View Code
  • 相关阅读:
    DataSet中的数据全部插入数据库
    SQL养成一个好习惯是一笔财富
    C#不管什么四舍五入,只要是小数取整就得加1
    XMLNode与XmlNodeList
    ASP.NET2.0中配置文件的加密与解密
    编写一个文件目录常用操作的类
    上传文件的方法
    使用javascript 实现.net 验证控件功能
    SQLSERVER如何获取一个数据库中的所有表的名称、一个表中所有字段的名称
    Android之开启内置闹钟与已安装的应用程序设置
  • 原文地址:https://www.cnblogs.com/ACRykl/p/8471743.html
Copyright © 2011-2022 走看看