题解 | #C~E#
小红的子序列求和
https://ac.nowcoder.com/acm/contest/80743/E
C 小红的素数合并
首先将数组排序,如果数组长度为奇数则最大项不参与合并,其余的贪心地让第i小的项与第i大的项合并即可,合并过程中更新最大最小值。
import sys, random
INF = float('inf')
input = lambda: sys.stdin.readline().rstrip("\r\n")
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
n = ii()
a = sorted(lmii())
mx, mn = 0, INF
if len(a) & 1:
mn = mx = a.pop()
n -= 1
for i in range(n // 2):
cur = a[i] * a[n - i - 1]
mn = min(mn, cur)
mx = max(mx, cur)
print(mx - mn)
D 小红的树上删边
从叶子节点向根节点计算子树大小,因为要删尽可能多的边,所以一旦发现偶数大小的子树立刻删掉该子树的根与其父亲节点的边,将该子树大小更新为零。如果最后根节点的字数大小为奇数,说明无法实现。
import sys, random
from types import GeneratorType
input = lambda: sys.stdin.readline().rstrip("\r\n")
ii = lambda: int(input())
mii = lambda: map(int, input().split())
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
n = ii()
g = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = mii()
g[u].append(v)
g[v].append(u)
sz = [-1] * (n + 1)
ans = 0
@bootstrap
def dfs(u, p):
global ans
for v in g[u]:
if v == p: continue
if sz[v] == -1: yield dfs(v, u)
sz[u] += sz[v]
if sz[u] % 2 == 0:
if u != 1:
ans += 1
sz[u] = 0
else:
if u == 1:
ans = -1
yield None
dfs(1, -1)
print(ans)
E 小红的子序列求和
注意到n和k很小,可以O(n^2),于是dp
表示遍历至第i个数时长度为j的数的和
@表示+
import sys, random
input = lambda: sys.stdin.readline().rstrip("\r\n")
mii = lambda: map(int, input().split())
lmii = lambda: list(map(int, input().split()))
mod = int(1e9 + 7)
n, k = mii()
a = [0] + list(map(int, list(input())))
dp = [[0] * (n + 1) for _ in range(n + 1)]
C = [[0] * 1001 for _ in range(1001)]
for i in range(n + 1):
C[i][0] = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
C[i][j] = C[i - 1][j] + C[i - 1][j - 1]
for i in range(1, n + 1):
for j in range(1, i + 1):
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] * 10 + a[i] * C[i - 1][j - 1]
dp[i][j] %= mod
print(dp[n][k])