用c++实现
时间: 2023-08-24 10:18:09 浏览: 35
好的,以下是C++代码实现:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
int prices[n];
for (int i = 0; i < n; i++) {
cin >> prices[i];
}
int R;
cin >> R;
sort(prices, prices+n); // 排序
int ans = 0;
for (int i = 0; i < n-2; i++) { // 枚举三个商品
for (int j = i+1; j < n-1; j++) {
for (int k = j+1; k < n; k++) {
int total = prices[i] + prices[j] + prices[k];
if (total <= R && total > ans) {
ans = total;
}
}
}
}
if (ans == 0) {
cout << 1 << endl;
} else {
cout << ans << endl;
}
return 0;
}
```
这里使用了数组来保存商品价格,然后也是按照上面的步骤来解决。需要注意的是,C++中需要先输入数组长度,然后再输入数组元素。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)