日期:2026年4月3日
ZeroJudge 題目連結:d056. 10013 - Super long sums
解題想法
這題如果用 Python 解題,最好用串列 a、b 儲存超長整數,再用另一個串列 ans 儲存計算結,串列資料格式為字串。運算時由 a、b 最後面住前讀取資料,將計算結果用字串格式存入 ans,輸出答案時將 ans 反序輸出。如果用 C++ 解題,可以用字串或 vector 儲存超長整數,用字串格式好像速度快一點。
Python 程式碼
使用時間約為 0.4 s,記憶體約為 141.1 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
n = int(data[ptr])
ptr += 1
for _ in range(n):
m = int(data[ptr])
ptr += 1
a, b = [], []
for _ in range(m):
c, d = map(int, data[ptr:ptr+2])
ptr += 2
a.append(c)
b.append(d)
ans = []
carry = 0
for i, j in zip(a[::-1], b[::-1]):
k = int(i) + int(j) + carry
if k >= 10:
carry = 1
ans.append(f"{k%10}")
else:
carry = 0
ans.append(f"{k}")
if carry == 1: ans.append("1")
res = "".join(ans[::-1])
if not result: result.append(f"{res}\n")
else: result.append(f"\n{res}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 26 ms,記憶體約為 8.2 MB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n; cin >> n;
for(int i=0; i<n; i++) {
int m; cin >> m;
string a, b;
for(int j=0; j<m; j++) {
char c, d; cin >> c >> d;
a += c; b += d;
}
string ans;
int carry = 0;
for(int j=m-1; j>=0; j--) {
int k = a[j]-'0' + b[j]-'0' + carry;
if (k >= 10) {
carry = 1;
ans += char(k%10 + '0');
} else {
carry = 0;
ans += char(k + '0');
}
}
if (carry == 1) ans += "1";
if (i > 0) cout << "\n";
for(auto it = ans.crbegin(); it != ans.crend(); it++) cout << *it;
cout << "\n";
}
return 0;
}
使用時間約為 85 ms,記憶體約為 15.7 MB,通過測試。
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n; scanf("%d", &n);
for(int i=0; i<n; i++) {
int m; scanf("%d", &m);
int a[m], b[m];
for(int j=0; j<m; j++) scanf("%d %d", &a[j], &b[j]);
vector<int> ans;
int carry = 0;
for(int j=m-1; j>=0; j--) {
int k = a[j] + b[j] + carry;
if (k >= 10) {
carry = 1;
ans.push_back(k%10);
} else {
carry = 0;
ans.push_back(k);
}
}
if (carry == 1) ans.push_back(1);
if (i > 0) puts("");
for(auto it = ans.crbegin(); it != ans.crend(); it++) printf("%d", *it);
puts("");
}
return 0;
}
沒有留言:
張貼留言