题解 | #kotori和素因子#

kotori和素因子

https://www.nowcoder.com/practice/7b1c858a3e7a41ed8364178979eaae67

import sys
input = sys.stdin.readline
n = int(input())
arr = list(map(int, input().strip().split()))
brr = []
// 检查是否质数, 推荐改用质数筛
def check(num):
    if num != 2:
        for i in range(2, num // 2 + 1):
            if num % i == 0:
                return False
        return True
    return True

boo = [False] * (max(arr) + 1)
// 选出所有可能使用到的质数
for i in range(2, max(arr) + 1):
    boo[i] = check(i)
// 选出每个数的因素数,并排序
for i in range(len(arr)):
    brr.append([])
    if boo[arr[i]]:
        brr[i].append(arr[i])
    for j in range(2, arr[i] // 2 + 1):
        if arr[i]%j == 0 and check(j):
            brr[i].append(j)
    brr[i].sort()
boo = [False] * (max(arr) + 1)

res = sum(arr) + 1
l = False
def dfs(pos, s):
    global res, l
    if pos == n:
        l = True
        res = min(res, s)
        return
    for i in brr[pos]:
        if s + i >= res:
            return
        if not boo[i]:
            boo[i] = True
            dfs(pos + 1, s + i)
            boo[i] = False
dfs(0, 0)
if l:
    print(res)
else:
    print(-1)

全部评论

相关推荐

10-09 16:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务