当前位置:   article > 正文

第十四届蓝桥杯国赛PythonB组B题【弹珠堆放】题解(AC)_第十四届蓝桥杯pythonb组

第十四届蓝桥杯pythonb组

在这里插入图片描述
在这里插入图片描述

题意分析

将一个长度 40 40 40 的数组 A A A 拆成两份 a , b a, b a,b,设 s 1 , s 2 s_1, s_2 s1,s2 分别表示数组 a , b a, b a,b 的和,求 s 1 × s 2 s_1 \times s_2 s1×s2 的最大值。

我们来考虑一下,什么情况下可以使得 s 1 × s 2 s_1 \times s_2 s1×s2 取得最大值。

设数组 A A A 的和为 s s s,设数组 a a a 的和为 x x x,那么数组 b b b 的和就为 s − x s - x sx s 1 × s 2 = x × ( s − x ) = x 2 − s x s_1 \times s_2 = x \times(s-x) = x^2 - sx s1×s2=x×(sx)=x2sx,函数大致如下:

在这里插入图片描述
x = s 2 x = \dfrac s 2 x=2s x × ( s − x ) x \times (s - x) x×(sx) 取得最大值。

x x x 约趋近于 s 2 \dfrac s 2 2s,结果越大。

所以,现在任务转换为,将数组 A A A,拆成两个子数组,要求两个数组的和要尽可能接近。

法一

通过 dfs 进行爆搜,编码难度较大,较容易出错。

法二

通过 dp 确认哪些和是可以被构建出来的。

f [ i ] [ j ] f[i][j] f[i][j] 表示前 i i i 个数,能否凑出一个和为 j j j 的数组。

考虑第 i i i 个数,若对于某个 f [ i − 1 ] [ j ] f[i-1][j] f[i1][j]True

  • 不用第 i i i 个数:前 i − 1 i-1 i1 个数可以凑出 j j j,那么前 i i i 个数也一定可以凑出 j j j,即 f [ i ] [ j ] = T r u e f[i][j] = True f[i][j]=True
  • 用第 i i i 个数:用前 i − 1 i-1 i1 个数可以凑出 j j j,那么前 i i i 个数就可以凑出 j + w [ i ] j+w[i] j+w[i],即 f [ i ] [ j + w [ i ] = T r u e f[i][j + w[i] = True f[i][j+w[i]=True

另外本题可进行空间优化。

  • Python
import sys
sys.setrecursionlimit(1000000)
input = lambda:sys.stdin.readline().strip()

N = int(4e5 + 10)

a = [0, 5160, 9191, 6410, 4657, 7492, 1531, 8854, 1253, 4520, 9231, 1266, 4801, 3484, 4323, 5070, 1789, 2744, 5959, 9426, 4433, 4404, 5291, 2470, 8533, 7608, 2935, 8922, 5273, 8364, 8819, 7374, 8077, 5336, 8495, 5602, 6553, 3548, 5267, 9150, 3309]
n = 40

s = sum(a)
f = [[False for i in range(N)] for i in range(45)]

f[0][0] = True
for i in range(1, n + 1):
    for j in range(0, N - 1):
        if f[i - 1][j]:
            f[i][j] = f[i][j + a[i]] = True

t = s // 2
while not f[n][t]:
    t -= 1

print(t * (s - t))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • Python(滚动数组)
import sys
sys.setrecursionlimit(1000000)
input = lambda:sys.stdin.readline().strip()

N = int(4e5 + 10)

a = [5160, 9191, 6410, 4657, 7492, 1531, 8854, 1253, 4520, 9231, 1266, 4801, 3484, 4323, 5070, 1789, 2744, 5959, 9426, 4433, 4404, 5291, 2470, 8533, 7608, 2935, 8922, 5273, 8364, 8819, 7374, 8077, 5336, 8495, 5602, 6553, 3548, 5267, 9150, 3309]

s = sum(a)
f = [False for i in range(N)]

f[0] = True
for x in a:
    for i in range(N - 1, 0 - 1, -1):
        if f[i]:
            f[i + x] = True

t = s // 2
while not f[t]:
    t -= 1

print(t * (s - t))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

运行结果:

12873625444
  • 1

【在线测评】

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/728396
推荐阅读
相关标签
  

闽ICP备14008679号