2017软院金山WPS补题 L

比赛的时候题意看不懂。。
然后就卡了。。

L题

就是模拟操作系统的LRU算法。

就是维护一个链表,如果要替换的话就找到最后一个替换,如果要插入的话就插入到开头,如果在链表中已经存在的话,就把这个提到链表的开头,然后搞一下就行了。

看了别人的做法, 用的是queue+map
cnt与queue中的元素个数不是同步的 。’不过我觉得这样不是那么容易想到。。

标程, 应该是双向链表吧。。

//自己应该要会用map标记某个数出现的位置。。我居然想的时候用for查一遍
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

const int MaxN=100005;

int N,K;
map <int,int> rem;

int LL[MaxN],RR[MaxN],val[MaxN];
int cou;

char ans[MaxN];

inline void erase(int p) {
    RR[LL[p]]=RR[p];
    LL[RR[p]]=LL[p];
}

inline void insert(int p) {
    RR[p]=RR[0];
    LL[p]=0;

    LL[RR[0]]=p;
    RR[0]=p;
}

int main() {
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    int a,b;

    while(~scanf("%d %d",&N,&K)) {
        cou=0;
        RR[0]=K+1;
        LL[K+1]=0;
        rem.clear();
        ans[N]=0;

        for(int i=0;i<N;++i) {
            scanf("%d",&a);

            if(rem.count(a)) {
                ans[i]='1';

                b=rem[a];
                erase(b);
                insert(b);
            }
            else {
                ans[i]='0';

                if(cou<K) {
                    ++cou;
                    rem[a]=cou;
                    val[cou]=a;
                    insert(cou);
                }
                else {
                    b=LL[K+1];
                    rem.erase(val[b]);
                    rem[a]=b;

                    erase(b);
                    val[b]=a;
                    insert(b);
                }
            }
        }
        puts(ans);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值