(双子序列最大和)给定一个长度为 n(3≤n≤1000) 的整数序列,要求从中选出两个连续子序列,使得这两个连续子序列的序列和之和最大,最终只需输出这个最大和。一个连续子序列的序列和为该连续子序列中所有数之和。要求:每个连续子序列长度至少为 1,且两个连续子序列之间至少间隔 1 个数。(第五空 4 分,其余 2.5 分)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <iostrea m> using namespace std; const int MAXN = 1000; int n, i, ans, sum; int x[MAXN]; int lmax[MAXN]; // lmax[i] 为仅含 x[i] 及 x[i] 左侧整数的连续子序列的序列和中,最大的序列和 int rmax[MAXN]; // rmax[i] 为仅含 x[i] 及 x[i] 右侧整数的连续子序列的序列和中,最大的序列和 int main() { cin >> n; for (i = 0; i < n; i++) cin >> x[i]; lmax[0] = x[0] ; for (i = 1; i < n; i++) if (lmax[i - 1] <= 0) lmax[i] = x[i]; else lmax[i] = lmax[i - 1] + x[i]; for (i = 1; i < n; i++) if (lmax[i] < lmax[i - 1]) lmax[i] = lmax[i - 1]; ①; for (i = n - 2; i >= 0; i --) if (rmax[i + 1] <= 0) ②; else ③; for (i = n - 2; i >= 0; i --) if (rmax[i] < rmax[i + 1]) ④; ans = x[ 0] + x [2]; for (i = 1; i < n - 1; i++) { sum = ⑤; if (sum > ans) ans = sum; } cout << ans << endl; return 0; } |
0 of 5 Questions completed
Questions:
You have already completed the quiz before. Hence you can not start it again.
Quiz is loading…
You must sign in or sign up to start the quiz.
You must first complete the following:
0 of 5 Questions answered correctly
Your time:
Time has elapsed
You have reached 0 of 0 point(s), (0)
Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)
1、填空位置 ①
填空位置②
填空位置 ③
填空位置 ④
填空位置 ⑤