#46677: Python 滿分解


leyinglego@gmail.com (樂穎育教Leying Studio)

學校 : 弘文中學
編號 : 297840
來源 : [114.26.138.207]
最後登入時間 :
2025-01-08 20:28:19

from collections import Counter

def is_valid(new_point, points, counter):
temp = Counter(abs(new_point - p) for p in points)
for k in temp:
if temp[k] > counter[k]:
return False
return temp

def apply_diff(counter, usage):
for k in usage:
counter[k] -= usage[k]
if counter[k] == 0:
del counter[k]

def undo_diff(counter, usage):
for k in usage:
counter[k] += usage[k]

n = int(input())
diffs_input = list(map(int, input().split()))

# --- 處理 n=1 特例 ---
if n == 1:
print("0")
print("0")
exit()

# --- 處理 n=2 特例 ---
if n == 2:
d = diffs_input[0]
a = [0, d]
b = [d, 0]
a.sort()
b.sort()
print(' '.join(map(str, min(a, b))))
print(' '.join(map(str, max(a, b))))
exit()

# --- 一般情況 ---
diffs = diffs_input[:]
L = max(diffs)
diffs.remove(L)
counter = Counter(diffs)

results = set()
stack = [([0, L], counter.copy())]

while stack:
seq, remain = stack.pop()

if len(seq) == n:
results.add(tuple(sorted(seq)))
continue

d = max(remain)
candidates = set()
for p in seq:
candidates.add(p + d)
candidates.add(p - d)

for new_point in candidates:
if new_point in seq or not (0 <= new_point <= 100):
continue
usage = is_valid(new_point, seq, remain)
if usage:
apply_diff(remain, usage)
stack.append((seq + [new_point], remain.copy()))
undo_diff(remain, usage)

if results:
results = sorted(results)
print(' '.join(map(str, results[0])))
print(' '.join(map(str, results[-1])))
else:
print("No solution found")