用三分法求给定数组的最大值、最小值、数组的和的CPP代码
时间: 2023-03-27 18:04:51 浏览: 95
以下是用三分法求给定数组的最大值、最小值、数组的和的CPP代码:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 100005;
int n, a[MAXN];
int main() {
cin >> n;
for (int i = ; i < n; i++) {
cin >> a[i];
}
int l = , r = n - 1;
while (l < r) {
int mid1 = l + (r - l) / 3;
int mid2 = r - (r - l) / 3;
int sum1 = , sum2 = ;
for (int i = l; i <= mid1; i++) {
sum1 += a[i];
}
for (int i = mid2; i <= r; i++) {
sum2 += a[i];
}
if (sum1 < sum2) {
l = mid1 + 1;
} else {
r = mid2 - 1;
}
}
int max_val = a[l], min_val = a[l], sum = ;
for (int i = ; i < n; i++) {
max_val = max(max_val, a[i]);
min_val = min(min_val, a[i]);
sum += a[i];
}
cout << "最大值:" << max_val << endl;
cout << "最小值:" << min_val << endl;
cout << "数组的和:" << sum << endl;
return ;
}
```
阅读全文