题意分析
将一个长度 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 s−x, 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×(s−x)=x2−sx,函数大致如下:
当
x
=
s
2
x = \dfrac s 2
x=2s,
x
×
(
s
−
x
)
x \times (s - x)
x×(s−x) 取得最大值。
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[i−1][j] 为 True
:
- 不用第 i i i 个数:前 i − 1 i-1 i−1 个数可以凑出 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 i−1 个数可以凑出 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))
- 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))
运行结果:
12873625444