我正在尝试解决 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/