巧克力盛宴节目

标签 c algorithm

我正在尝试解决 the Chocolate Feast challenge on HackerRank :

Little Bob loves chocolate, and he goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?

Input Format: The first line contains the number of test cases, T. T lines follow, each of which contains three integers, N, C, and M.

Output Format: Print the total number of chocolates Bob eats.

Constraints:

1≤T≤1000 
2≤N≤105 
1≤C≤N 
2≤M≤N

Sample input:

3
10 2 5
12 4 4
6 2 2

Sample Output:

6
3
5

Explanation In the first case, he can buy 5 chocolates with $10 and exchange the 5 wrappers to get one more chocolate. Thus, the total number of chocolates is 6.

In the second case, he can buy 3 chocolates for $12. However, it takes 4 wrappers to get one more chocolate. He can't avail the offer and hence the total number of chocolates remains 3.

In the third case, he can buy 3 chocolates for $6. Now he can exchange 2 of the 3 wrappers and get 1 additional piece of chocolate. Now he can use his 1 unused wrapper and the 1 wrapper of the new piece of chocolate to get one more piece of chocolate. So the total is 5.

这是我在 C 中尝试的解决方案:

#include<stdio.h>
int main(){
    int t; //total test cases
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){
        int n; //money
        int c; //cost of 1 chocolate
        int m; //no of wrappers to buy a new chocolate
        scanf("%d %d %d",&n,&c,&m);
        int tc=0,nw=0,nc=0,w=0;//tc=totalChocolates  nw=newWrappers nc=newChocolates w=wrappers
        tc=n/c;
        w=tc;
        while(w>=m){
            nc=(w/m);
            tc+=nc;
            w-=m;
            nw=w%m;
            w+=nw;
        }
        printf("%d\n",tc);    
    }
    return 0;
}

问题是我的程序通过了一些测试用例,而在其他一些测试用例中却失败了,但我无法找到错误所在。 此外,对于其他一些测试,所用时间超过 2 秒。

Test case
Input
Excepted output

最佳答案

你的逻辑有点困惑:

    while(w>=m){
        nc=(w/m);
        tc+=nc;
        w-=m;
        nw=w%m;
        w+=nw;
    }

如果你把它改成这样,那么它会通过所有的测试用例:

    while(w>=m){
        nc=(w/m);     // how many additional bars can we buy ?
        tc+=nc;       // accumulate total bars purchased
        w-=(nc*m);    // deduct no of wrappers used to purchase additional bars
        w+=nc;        // accumulate additional wrappers
    }

关于巧克力盛宴节目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936677/

相关文章:

c++ - 0xDEADBEEF 与 NULL

c - 段错误: 11 for C

algorithm - 在 O(nlog(range of bounds)) 时间内优化列表中的最大值

algorithm - α-β 修剪算法 - 完美的叶节点顺序应该是什么,哪种 alpha-beta 算法修剪尽可能多的节点?

Java 冒泡排序具有 3 个元素的反向排序数组。

c - 字符串初始化的 gcc 诊断不一致

c++ - GCC如何处理变量重定义

按下按钮时,移动 Sprite 的方向改变 90 度,表现奇怪

c++ - 程序生成的伪随机

python - 将树中的权重从叶更新到根时出错