日期:2026年2月12日
ZeroJudge 題目連結:c060. 00392 - Polynomial Showdown
解題想法
這題要考慮各種顯示的格式,很麻煩。
Python 程式碼
使用時間約為 19 ms,記憶體約為 3.4 MB,通過測試。
import sys
# 各次方要顯示的變數格式
orders = ("", "x", "x^2", "x^3", "x^4", "x^5", "x^6", "x^7", "x^8")
for line in sys.stdin:
cofs = list(map(int, line.split())) # 8 ~ 0 次方的係數
if all(cof == 0 for cof in cofs): # 特例,如果所有的係數都是 0
print("0") # 印出 0
continue # 找下一行
""" 處理一般的狀況 """
res = [] # 儲存結果用的串列
for i, cof in enumerate(cofs): # 依序讀取係數
p = 8-i # 次方
if cof == 0: continue # 係數是 0,找下一位
if cof > 1: # 係數大於 1
if res: # 如果 res 已經有內容,前面要有 " + "
res.append(f" + {cof:d}{orders[p]:s}")
else: # 反之,前面不需要有 " + ",只要有係數、變數、次方
res.append(f"{cof:d}{orders[p]:s}")
elif cof == 1: # 係數等於 1
if res: # 如果 res 已經有內容,前面要有 " + "
if p == 0: res.append(" + 1") # 常數項,只要有 " + 1"
else: res.append(f" + {orders[p]:s}") # 其它項,只要有 " + 變數、次方"
else: # 反之,前面不需要有 " + "
if p == 0: res.append("1") # 常數項,只要有 "1"
else: res.append(f"{orders[p]:s}") # 其它項,只要有變數、次方
elif cof == -1: # 係數等於 -1
if res: # 如果 res 已經有內容,前面要有 " - "
if p == 0 res.append(" - 1") # 常數項,只要有 " - 1"
else: res.append(f" - {orders[p]:s}") # 其它項,只要有 " - 變數、次方"
else: # 反之,前面不需要有 " - "
if p == 0: res.append("-1") # 常數項,只要有 "-1"
else: res.append(f"-{orders[p]:s}") # 其它項,只要有 "-變數、次方"
elif cof < -1: # 係數小於 -1
if res: # 如果 res 已經有內容,前面要有 " - "
res.append(f" - {-cof:d}{orders[p]:s}")
else: # 反之,前面不需要有 " - ",只要有係數、變數、次方
res.append(f"{cof:d}{orders[p]:s}")
print("".join(res)) # 將 res 接成字串再輸出