H - 加算と乗算 / Addition and Multiplication Editorial
by
hirayuu_At
楽な実装
Pythonを使うことで楽に実装することができます。
\(A\) の並び替え、演算子の全列挙はどちらも itertools
にある関数 permutations
, product
を使って実現できます。
数式の文字列を作るのはさほど難しくありません。作った後、eval
関数でそれを式として評価できます(おそらく、この問題の最も難しい部分をこうしてスキップすることができます)。\(S\) が返ったら、replace
関数を使って *
を x
に置き換えたのち出力すればよいです。
実装例 (PyPy3)
from itertools import permutations,product
N,S=map(int,input().split())
A=list(map(int,input().split()))
for a in permutations(A):
for ope in product(["+","*"],repeat=N-1):
now=str(a[0])
for i in range(N-1):
now+=ope[i]+str(a[i+1])
if eval(now)==S:
print("Yes")
print(now.replace("*","x"))
exit()
print("No")
posted:
last update: