【出题】信息技术选考 T15
15.(
一个序列的非空连续子序列可以用两个下标
例如,当原序列为
解决该问题有许多算法。一种很容易想到一种做法如下。请在
【算法一】
def getmax(l, r):
ret = n
for i in range(l, r + 1):
if (a[i] > a[ret]):
ret = i
return ret
a = list(map(int, input().split()))
n = len(a)
(1)
sum = 0
for l in range(0, n):
for r in range(l, n):
sum += a[getmax(l, r)]
print(sum)
考虑这样一个事实:如果我们已经找到了一个序列的最大值所在的位置
【算法二】
def solve(l, r):
if (l > r):
return 0
mid = getmax(l, r)
return solve(l, mid - 1) + solve(mid + 1, r) + (2)
ans = solve(0, n - 1)
(3)时间复杂度分析。算法一、算法二的时间复杂度分别为__。(
A.
B.
C.
D.
调用 getmax(l,r) 函数时需要查询子序列
一种更高效的做法如下。我们定义
已知:x << y 表示将整数 x << y 等于 x << y 表示将整数 x >> y 等于
def Init():
N, M = 1 << 17, 17
Log = [0] * N
for i in range(0, n):
f[i][0] = a[i]
for i in range(2, n + 1):
Log[i] = Log[i >> 1] + 1
for j in range(1, Log[n] + 1):
i = 0
while (i + (1 << j) <= n):
f[i][j] = max(f[i][j - 1], (4))
i += 1
计算出 getmax(l, r) 函数了。请仔细思考,在
def getmax_op(l, r):
t = Log[r - l + 1]
return max(f[l][t], (5))
算法二启示我们,其实不需要枚举出每一个子序列,可以换一种思路,计算出原序列每一个数字对于答案的贡献。即,这个数字能成为多少子序列的最大值。在算法实现中,我们可以求出原序列中第
【算法三】
a = list(map(int, input().split()))
n = len(a)
L = [0] * n
R = [0] * n
st = [0] * n
ans, top = 0, -1
for i in range(0, n):
while (X):
top -= 1
if (top >= 0):
L[i] = st[top] + 1
else:
L[i] = 0
top += 1
st[top] = i
top = -1
for i in range(n - 1, -1, -1):
while (Y):
top -= 1
if (top >= 0):
R[i] = st[top] - 1
else:
R[i] = n - 1
top += 1
st[top] = i
for i in range(n):
print(L[i], R[i])
ans += a[i] * (R[i] - i + 1) * (i - L[i] + 1)
print(ans)
(6)X, Y 处合适的代码为:(
A. top > -1 and a[st[top]] <= a[i]; top > -1 and a[st[top]] <= a[i]
B. top > -1 and a[st[top]] <= a[i]; top > -1 and a[st[top]] < a[i]
C. top > -1 and a[st[top]] >= a[i]; top > -1 and a[st[top]] >= a[i]
D. top > 0 and a[st[top]] >= a[i]; top > 0 and a[st[top]] > a[i]