a970中等

97 全國資訊學科能力競賽(2008)|2. 線串式主題閱讀系統

輸出最早兩個主題線串。

解題思路

逐篇讀三個欄位。Subject: 後固定一空白屬於欄位前綴,先移除;內容若一開始是 Re: 或 RE:,只去掉一次,最後只去除兩端 ASCII 空白。

日期轉成(year,month,day,hour),再加原出現序號作為排序鍵。以正規化主題分組,每組依完整鍵排序。

每組的第一篇是它的最早日期及平手先後;依這個鍵排序線串後取前兩組。字串其他內容含大小寫、Unicode字元均保留。最後依格式輸出ID逗號列表與空白行。

L是全部文字長度,O(L+A log A) 時間、O(L+A) 空間。 Python一次讀入另佔O(輸入文字長度)空間。

Step-by-step animation

示例:Subject: Re: Re: X 只去掉第一組。

回報動畫錯誤
步驟 1 / 3

原主題

Subject: Re: Re: X 只去掉第一組。

Re: Re: X
去一次後
Re: X

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
struct A {
    array<int, 5> key;
    string id;
};
int main() {
    string s, date, id;
    map<string, vector<A>> g;
    int idx = 0;
    while (getline(cin, s)) {
        if (s.empty())
            continue;
        if (s.rfind("Subject: ", 0) != 0)
            continue;
        string t = s.substr(9);
        if (t.rfind("Re:", 0) == 0 || t.rfind("RE:", 0) == 0)
            t = t.substr(3);
        size_t a = t.find_first_not_of(' '), b = t.find_last_not_of(' ');
        t = a == string::npos ? "" : t.substr(a, b - a + 1);
        getline(cin, date);
        getline(cin, id);
        int m, d, h, y;
        istringstream in(date.substr(6));
        in >> m >> d >> h >> y;
        g[t].push_back({{y, m, d, h, idx++}, id.substr(4)});
    }
    vector<pair<array<int, 5>, string>> order;
    for (auto &[t, v] : g) {
        sort(v.begin(), v.end(), [](A a, A b) { return a.key < b.key; });
        order.push_back({v[0].key, t});
    }
    sort(order.begin(), order.end());
    for (int k = 0; k < 2; k++) {
        if (k)
            cout << '\n';
        string t = order[k].second;
        cout << "Subject: " << t << "\nID: ";
        auto &v = g[t];
        for (int j = 0; j < (int)v.size(); j++) {
            if (j)
                cout << ',';
            cout << v[j].id;
        }
        cout << '\n';
    }
    cout << "\n\n";
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多