从三个堆中选择最多石子的C++代码
假设我们有三个数字a、b和c。有三个石堆,分别有a、b和c个石子。每次我们可以执行以下操作:
从第一个堆中取走一个石子,从第二个堆中取走两个石子(当堆中有足够的石子时)
从第二个堆中取走一个石子,从第三个堆中取走两个石子(当堆中有足够的石子时)
我们必须计算最多可以收集多少石子?
因此,如果输入为a = 3;b = 4;c = 5,则输出为9,因为在两次操作中,我们可以从第二个堆中取走两个石子,从第三个堆中取走四个石子,总共得到6个石子,然后从第一个堆中取走一个,从第二个堆中取走两个,再得到3个石子。
步骤
为了解决这个问题,我们将遵循以下步骤:
return (minimum of b and floor of (c / 2) + minimum of a and (b - minimum of b and floor of (c / 2)) / 2) * 3
示例
让我们来看下面的实现以更好地理解:
#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b, int c){
return (min(b, c / 2) + min(a, (b - min(b, c / 2)) / 2)) * 3;
}
int main(){
int a = 3;
int b = 4;
int c = 5;
cout << solve(a, b, c) << endl;
}输入
3, 4, 5
输出
9
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP