b731簡單

髒頁的最近使用快取

對快取內每頁保存最後存取時戳及髒旗標。命中時只更新時戳,寫入再把髒位設真;讀取不得清除已存在的髒位。未命中且已滿時,移除時戳最小頁,只有其為髒頁才加一次回寫。

解題思路

對快取內每頁保存最後存取時戳及髒旗標。命中時只更新時戳,寫入再把髒位設真;讀取不得清除已存在的髒位。未命中且已滿時,移除時戳最小頁,只有其為髒頁才加一次回寫。

新載入的頁先為乾淨,再依本次是否寫入更新。每個操作結束後,時戳恰好反映該頁最後被操作的順序,所以取最小值完全等價於LRU。結束後只統計尚存髒頁,不沖刷快取。容量最多50,直接掃描淘汰者已足夠。

時間 O(MC)、空間 O(C+M),C≤50、M≤150,最壞7500次頁比較;Python 分詞輸入 O(M),快取 O(C)。

Step-by-step animation

自訂小例:C=1,W 1 未命中並留下髒頁。

回報動畫錯誤
步驟 1 / 3

步驟 1:寫頁1

C=1,W 1 未命中並留下髒頁。

1:髒
未命中
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int C, M;
    cin >> C >> M;
    map<ll, pair<int, bool>> cache;
    int hit = 0, miss = 0, back = 0;
    for (int t = 0; t < M; t++) {
        char op;
        ll x;
        cin >> op >> x;
        if (cache.count(x))
            hit++;
        else {
            miss++;
            if (cache.size() == (size_t)C) {
                auto it = min_element(cache.begin(), cache.end(), [](auto &a, auto &b) {
                    return a.second.first < b.second.first;
                });
                back += it->second.second;
                cache.erase(it);
            }
            cache[x] = {t, false};
        }
        cache[x] = {t, cache[x].second || op == 'W'};
    }
    int dirty = 0;
    for (auto [x, v] : cache)
        dirty += v.second;
    cout << hit << ' ' << miss << ' ' << back << ' ' << dirty << '\n';
}

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

更多