JSOI2010 && BZOJ1826 缓存交换

洛谷

BZOJ

分析

贪心策略很好想,显然,当 \(cache\) 未满时,直接放进去就行了; \(cache\) 满了的时候,考虑交换哪一个,不难看出可以交换下一次出现最晚的那个。

注意:不开 \(map\) 过不了!

代码

#include <map>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define il inline
#define re register
#define maxn 100005
#define tie0 cin.tie(0),cout.tie(0)
#define fastio ios::sync_with_stdio(false)
#define File(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

template <typename T> inline void read(T &x) {
    T f = 1; x = 0; char c;
    for (c = getchar(); !isdigit(c); c = getchar()) if (c == '-') f = -1;
    for ( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
    x *= f;
}

priority_queue <P> q;
map <int, int> lst, inq;

int n, m, ans;
int a[maxn], nxt[maxn];

int main() {
    memset(nxt, 1, sizeof(nxt));
    read(n), read(m);
    for (int i = 1; i <= n; ++i) {
        read(a[i]);
        nxt[lst[a[i]]] = i;
        lst[a[i]] = i;
    }
    for (int i = 1; i <= n; ++i) {
        if (inq[a[i]]) {
            q.push(make_pair(nxt[i], a[i]));
            m++;
            continue;
        }
        if (q.size() < m) {
            q.push(make_pair(nxt[i], a[i]));
            ans++; inq[a[i]] = 1;
            continue;
        }
        int k = q.top().second; q.pop();
        inq[k] = 0;
        q.push(make_pair(nxt[i], a[i]));
        inq[a[i]] = 1;
        ans++;
    }
    printf("%d", ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hlw1/p/11437155.html