熱門文章

2025年12月23日 星期二

ZeroJudge 解題筆記:a158. 11827 - Maximum GCD

作者:王一哲
日期:2025年12月23日


ZeroJudge 題目連結:a158. 11827 - Maximum GCD

解題想法


這題每一行測資讀取的數字數量不固定,因為 Python 都是一次讀取一行資料,寫法沒有差異;但是 C++ 讀取資料時比較麻煩,需要用 getline 一次讀取一行字串 s,再將 s 存入 stringstream 物件 ss,最後用 while 迴圈將 ss 之中的資料一次取一個出來存入 vector 之中。

Python 程式碼


使用時間約為 0.1 s,記憶體約為 3 MB,通過測試。
import sys, math

result = []
lines = sys.stdin.readlines()
idx = 1
while idx < len(lines):
    if not lines[idx].strip():
        idx += 1
        continue
    nums = tuple(map(int, lines[idx].split()))
    idx += 1
    m = len(nums)
    ans = 1
    for i in range(m-1):
        for j in range(i+1, m):
            ans = max(ans, math.gcd(nums[i], nums[j]))
    result.append(f"{ans:d}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 15 ms,記憶體約為 352 kB,通過測試。
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n; cin.ignore();
    string s;
    while(n--) {
        vector<int> nums;
        getline(cin, s);
        stringstream ss (s);
        while(ss >> s) nums.push_back(stoi(s));
        int m = (int)nums.size(), ans = 1;
        for(int i=0; i<m-1; i++) {
            for(int j=i+1; j<m; j++) {
                ans = max(ans, __gcd(nums[i], nums[j]));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}


沒有留言:

張貼留言