Codeforces 546A 士兵與香蕉 – 翻譯與解答

難易度 : 800

英文原文如下

A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).

He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?

中文翻譯

一個士兵想要在商店購買 w 根香蕉。他需要為了第一根香蕉付 k 元, 第二根則是 2k 元,以此類推。 (用另一種話說,第 i-th 根香蕉時他需要支付 i*k 元)

他有 n 元,要是他想要購買 w 根香蕉,他需要跟士兵朋友再借多少元呢?

輸入

The first line contains three positive integers k, n, w (1  ≤  k, w  ≤  1000, 0 ≤ n ≤ 109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.

第一行包含了三個正整數 k, n, w (1  ≤  k, w  ≤  1000, 0 ≤ n ≤ 109),分別是

  • k : 第一根香蕉的價錢
  • n : 士兵身上有的錢
  • w : 他想要購買多少單位的香蕉

輸出

Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn’t have to borrow money, output 0.

印出一個整數 – 士兵需要向朋友借的錢,要是他不需要借錢,則印出 0。

範例

輸入3 17 4
輸出13

解題思路

要從1+2+…到n,相信大家都知道有一個數學公式可以輕鬆計算吧

➡ 總和 = (1+n)*n/2

那知道這個我們就能很簡單的計算出答案了~

C#解決方案

方案1

string[] input = Console.ReadLine().Split(' '); //split by space
int k = int.Parse(input[0]);    //dollars per unit
int n = int.Parse(input[1]);    //the dollars he got
int w = int.Parse(input[2]);    //amount that he want to buy

int unit = (1+w)*w/2;
int price = unit*k;



Console.WriteLine(n>=price?0:price-n); 

Java解決方案

方案1

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] input = scanner.nextLine().split(" ");

        int k = Integer.parseInt(input[0]);    //dollars per unit
        int n = Integer.parseInt(input[1]);    //the dollars he got
        int w = Integer.parseInt(input[2]);    //amount that he want to buy
        
        int unit = (1+w)*w/2;
        int price = unit*k;
        
        System.out.println(n>=price?0:price-n);
        
    }
}

結論

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 546A – Codeforces

一些其他的文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *