b322中等

98 臺北市資訊學科能力競賽(2009)|購物網站

統計最高同時登入活動及對應分鐘區間。

解題思路

統計最高同時登入活動及對應分鐘區間。

登入登出皆包含端點,對裁切到[S,E]的登入區間[l,r]在diff[l]加1、diff[r+1]減1。

掃描前綴得到每分鐘活動數,先找最大值,再合併相鄰的達峰分鐘成閉區間。

購買僅檢查時間是否在[S,E],按品項累計,輸出全部最高者;沒有任何購買就輸出?。同帳號不同紀錄分別計數。

時間 O(n+購買筆數+1440),空間 O(1440),逐行處理;Python單行儲存該筆所有購買。

Step-by-step animation

兩個活動[1,3]與[3,5]的端點重疊示例

回報動畫錯誤
步驟 1 / 3

步驟 1

示例時段0至10,活動[1,3]及[3,5]。

1 2 3
3 4 5
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n, S, E;
    cin >> n >> S >> E;
    vector<int> d(1442), f(26);
    while (n--) {
        int id, l, r, k;
        cin >> id >> l >> r >> k;
        l = max(l, S);
        r = min(r, E);
        if (l <= r) {
            d[l]++;
            d[r + 1]--;
        }
        while (k--) {
            int t;
            char c;
            cin >> t >> c;
            if (S <= t && t <= E)
                f[c - 'A']++;
        }
    }
    vector<int> a(1440);
    int sum = 0, mx = 0;
    for (int i = 0; i < 1440; i++) {
        sum += d[i];
        a[i] = sum;
        if (S <= i && i <= E)
            mx = max(mx, sum);
    }
    cout << mx << '\n';
    bool first = true;
    for (int i = S; i <= E; i++)
        if (a[i] == mx) {
            int j = i;
            while (j + 1 <= E && a[j + 1] == mx)
                j++;
            if (!first)
                cout << ' ';
            first = false;
            cout << i << ' ' << j;
            i = j;
        }
    cout << '\n';
    mx = *max_element(f.begin(), f.end());
    if (!mx)
        cout << '?';
    else {
        first = true;
        for (int i = 0; i < 26; i++)
            if (f[i] == mx) {
                if (!first)
                    cout << ' ';
                first = false;
                cout << char('A' + i);
            }
    }
    cout << '\n';
}

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

更多