-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsum_41_chapter_1-2.py3
31 lines (27 loc) · 972 Bytes
/
sum_41_chapter_1-2.py3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Copyright (c) 2023 kamyu. All rights reserved.
#
# Meta Hacker Cup 2023 Round 1 - Problem B1. Sum 41 (Chapter 1)
# https://www.facebook.com/codingcompetitions/hacker-cup/2023/round-1/problems/B1
#
# Time: O(backtracking_nodes(K) + K^2) = O(partitions(K)*2 + K^2) = O(89166 + K^2), K = 41
# Space: O(K)
#
from itertools import chain
def sum_41_chapter_1():
def backtracking(total, product):
if total == 0:
return product == 1
for i in chain(range(result[-1] if result else 1, total//2+1), [total]):
if product%i:
continue
result.append(i)
if backtracking(total-i, product//i):
return True
result.pop()
return False
P = int(input())
result = []
return f'{len(result)} {" ".join(map(str, result))}' if backtracking(TARGET, P) else -1
TARGET = 41
for case in range(int(input())):
print('Case #%d: %s' % (case+1, sum_41_chapter_1()))