日期:2025年11月25日
ZeroJudge 題目連結:j568. 無預警小考 ( 上 )
解題想法
按照題目要求的格式組合答案。我在 Python 先將所有要輸出的內容用字串格式儲存在串列之中,最後再接成很長的字串用 sys.stdout.write 輸出;在 C++ 則是每組合完一小段答案就用 cout 輸出。
Python 程式碼
使用時間約為 5.6 s,記憶體約為 3.4 MB,通過測試。
import sys
t = int(sys.stdin.readline())
for _ in range(t):
result = ["請使用配方法解下列一元二次方程式\n\n"]
n = int(sys.stdin.readline())
for i in range(1, n+1):
cof = list(map(int, sys.stdin.readline().split()))
eq = str(i) + ". "
if cof[0] == 1: eq += "x^2"
elif cof[0] == -1: eq += "-x^2"
else: eq += str(cof[0]) + "x^2"
if cof[1] == 0: pass
elif cof[1] == 1: eq += "+x"
elif cof[1] > 1: eq += "+" + str(cof[1]) + "x"
elif cof[1] == -1: eq += "-x"
else: eq += str(cof[1]) + "x"
if cof[2] == 0: pass
elif cof[2] > 0: eq += "+" + str(cof[2])
else: eq += str(cof[2])
eq += "=0\n\n"
result.append(eq)
result.append("考試要加油口屋\n\n")
sys.stdout.write("".join(result))
C++ 程式碼
使用時間約為 1.4 s,記憶體約為 348 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int t; cin >> t;
while(t--) {
cout << "請使用配方法解下列一元二次方程式\n\n";
int n; cin >> n;
for(int i=1, cof; i<=n; i++) {
cout << i << ". ";
cin >> cof; // 平方項係數
if (cof == 1) cout << "x^2";
else if (cof == -1) cout << "-x^2";
else cout << cof << "x^2";
cin >> cof; // 一次項係數
if (cof == 0) ; // do nothing
else if (cof == 1) cout << "+x";
else if (cof > 1) cout << "+" << cof << "x";
else if (cof == -1) cout << "-x";
else cout << cof << "x";
cin >> cof; // 常數項
if (cof == 0) ; // do nothing
else if (cof > 0) cout << "+" << cof;
else cout << cof;
cout << "=0\n\n";
}
cout << "考試要加油口屋\n\n";
}
return 0;
}
沒有留言:
張貼留言