Loading [MathJax]/jax/output/HTML-CSS/jax.js

熱門文章

2025年4月26日 星期六

ZeroJudge 解題筆記:k467. 分班 (Class)

作者:王一哲
日期:2025年4月26日



ZeroJudge 題目連結:k467. 分班 (Class)

解題想法


這題要同時比較同一個人的語文及數理成績,在 Python 可以用 zip 將兩行資料合併再一起輸出,在 C++ 則可以先儲存語文成績在一個陣列之中,再依序讀取每個人的數理成績,不需要儲存,可以少用一點記憶體。

Python 程式碼


使用時間約為 31 ms,記憶體約為 3.6 MB,通過測試。
import sys

for line in sys.stdin:
    n = int(line)  # n 個人
    lan, sci = [], []  # 語文班、數理班座號
    # 讀取兩行資料,用 zip 綁在一起輸出,兩個分數 a, b,編號從 1 開始,
    for i, (a, b) in enumerate(zip(map(int, input().split()), map(int, input().split())), start=1):
        if a > b: lan.append(i)  # a 大,i 加入 lan
        else: sci.append(i)  # b 大,i 加入 sci
    if lan: print(*lan)
    else: print(-1)
    if sci: print(*sci)
    else: print(-1)


C++ 程式碼


使用時間約為 3 ms,記憶體約為 280 kB,通過測試。
#include <cstdio>
#include <vector>
using namespace std;

int main() {
    int n;  // n 個人
    while(scanf("%d", &n) != EOF) {
        vector<int> lan, sci;  // 語文班、數理班座號
        int a[n];  // 每個學生的語文分數
        for(int i=0; i<n; i++) scanf("%d", &a[i]);
        for(int i=0; i<n; i++) {
            int b; scanf("%d", &b);  // 這個學生的數理分數
            if (a[i] > b) lan.push_back(i+1);  // a 大,i+1 加入 lan
            else sci.push_back(i+1);  // b 大,i+1 加入 sci
        }
        if (lan.empty()) {
            printf("-1\n");  // 如果語文班沒有人,印出 -1
        } else {
            for(int i=0; i<(int)lan.size(); i++) {
                printf("%d", lan[i]);
                if (i == (int)lan.size()-1) printf("\n");
                else printf(" ");
            }
        }
        if (sci.empty()) {
            printf("-1\n");  // 如果數理班沒有人,印出 -1
        } else {
            for(int i=0; i<(int)sci.size(); i++) {
                printf("%d", sci[i]);
                if (i == (int)sci.size()-1) printf("\n");
                else printf(" ");
            }
        }
    }
    return 0;
}

改用 cin, cout 輸入、輸出,使用時間約為 3 ms,記憶體約為 364 kB,通過測試。
#include <iostream>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n;  // n 個人
    while(cin >> n) {
        vector<int> lan, sci;  // 語文班、數理班座號
        int a[n];  // 每個學生的語文分數
        for(int i=0; i<n; i++) cin >> a[i];
        for(int i=0; i<n; i++) {
            int b; cin >> b;  // 這個學生的數理分數
            if (a[i] > b) lan.push_back(i+1);  // a 大,i+1 加入 lan
            else sci.push_back(i+1);  // b 大,i+1 加入 sci
        }
        if (lan.empty()) {
            cout << "-1\n";  // 如果語文班沒有人,印出 -1
        } else {
            for(int i=0; i<(int)lan.size(); i++) cout << lan[i] << " \n"[i == (int)lan.size()-1];
        }
        if (sci.empty()) {
            cout << "-1\n";  // 如果數理班沒有人,印出 -1
        } else {
            for(int i=0; i<(int)sci.size(); i++) cout << sci[i] << " \n"[i == (int)sci.size()-1];
        }
    }
    return 0;
}


沒有留言:

張貼留言