设有一组数,其排列形式为:8,5,13,15,3,11,6,7,22,10,且尾部的10和头部的8首尾相连构成一个环形,编程求出相邻的任意四个数之和并输出,然后找出相加之和最大的四个数,输出求和的结果以及这四个数
时间: 2023-11-23 18:07:42 浏览: 79
好的,以下是代码实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
const int N = 11;
int a[N] = {8, 5, 13, 15, 3, 11, 6, 7, 22, 10, 8};
int main()
{
vector<int> sums;
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = i; j < i + 4; j++) {
sum += a[j % N];
}
sums.push_back(sum);
cout << sum << " ";
}
cout << endl;
int max_sum = 0, max_idx = 0;
for (int i = 0; i < N; i++) {
int sum = sums[i % N] + sums[(i + 1) % N] + sums[(i + 2) % N] + sums[(i + 3) % N];
if (sum > max_sum) {
max_sum = sum;
max_idx = i;
}
}
cout << "Max Sum: " << max_sum << endl;
cout << "Four numbers: ";
for (int i = max_idx; i < max_idx + 4; i++) {
cout << a[i % N] << " ";
}
cout << endl;
return 0;
}
```
这段代码首先计算相邻的任意四个数之和,并输出结果。然后遍历所有四个数的组合,找出相加之和最大的四个数,并输出求和的结果以及这四个数。
阅读全文