空瓶换新酒

空瓶换新酒

小区便利店正在促销,用 numExchange 个空酒瓶(>1)可以兑换一瓶新酒。你购入了 numBottles 瓶酒。

如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。

请你计算 最多能喝到多少瓶酒。(不可以赊账,可以思考如何使用\(O(1)\)的方法来解决)

1
2
3
4
5
6
7
8
9
input:
T //测试样例总数:
numBottles numExchange

示例:
输入:
9 3
输出:
13

递归法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;
int numWaterBottles(int numBottles, int numExchange){
if(numBottles < numExchange){
return numBottles;
}
int drunk = numBottles - numBottles % numExchange;
return numWaterBottles(numBottles / numExchange+numBottles % numExchange, numExchange) + drunk;
}
int main(){
int numBottles,numExchange;
cin>>numBottles>>numExchange;
cout<<numWaterBottles(numBottles, numExchange);
}

O(1)法

bottle
1
2
3
4
5
6
7
#include<iostream>
using namespace std;
int main(){
int numBottles,numExchange;
cin>>numBottles>>numExchange;
cout<<(numBottles * numExchange-1)/(numExchange-1)<<endl;
}

空瓶换新酒
https://wuhlan3.github.io/2020/10/29/空瓶换新酒/
Author
Wuhlan3
Posted on
October 29, 2020
Licensed under