zoukankan      html  css  js  c++  java
  • LRU算法的实现(STL+模拟)

    题目链接:传送门

    解题思路:

    我们可以开两个map和一个vector进行操作,第一个vis表示元素是否在容器里面,第二个mp表示的是键值对,第三个Vector的V表示的是最近访问的内容,值得注意的是,除了vis操作,其他的操作都不会让k变为最近访问,(因为这个wa了好几次),还有就是vis、pop、remove操作,如果不存在对应的内容,则不操作,最后注意多组输入要把这三个容器的东西清空

    code:

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<queue>
    #include<map>
    #define ll long long
    using namespace std;
    map<ll,bool> vis;//判断是否存在容器里面
    map<ll,ll> mp;
    vector<int> V;
    int main()
    {
    	int n;
    	while(~scanf("%d",&n)) {
    	getchar();
    	ll k;
    	ll v;
    	char op[30];
    	while(n--) {
    		scanf("%s",op);
    		getchar();
    		if(strcmp(op,"insert") == 0) {
    			scanf("%lld%lld",&k,&v);
    			getchar();
    			mp[k] = v;
    			if(!vis[k])
    				vis[k] = true,V.push_back(k);
    		}
    		else if(!strcmp(op,"get")) {
    			scanf("%lld",&k);
    			getchar();
    			if(vis[k]) {
    				printf("%lld
    ",mp[k]);
    			}
    			else {
    				puts("-1");
    			}
    		}
    		else if(!strcmp(op,"vis")) {
    			scanf("%lld",&k);
    			getchar();
    			auto loc = find(V.begin(),V.end(),k);//注意这里不能用lower_bound,因为V不一定有序
    			if(loc!= V.end() && *loc == k) {
    				V.erase(loc);
    				V.push_back(k);
    			}
    		}
    		else if(!strcmp(op,"pop")) {
    			if(V.size()) {//先判断V是否是空的,否则会RE
    				mp[V.front()] = -1ll,vis[V.front()] = false;
    				V.erase(V.begin());
    			}
    		}
    		else if(!strcmp(op,"remove")) {
    			scanf("%lld",&k);
    			getchar();
    			auto loc = find(V.begin(),V.end(),k);
    			if(loc!= V.end() && *loc == k) {
    				V.erase(loc);
    				mp[k] = -1ll;
    				vis[k] = false;
    			}
    		}
    	}
    	vis.clear();//注意清空STL的容器
    	V.clear();
    	mp.clear();
    
    }
    	return 0;
    }
    
  • 相关阅读:
    记一次struts项目空指针异常
    struts2问题(已解决)java.nio.file.InvalidPathException: Illegal char <:> at index 3: jar:file:
    Road Map
    API
    Report of program history
    正则表达式验证用户信息
    RegExp( replace()的示例 )
    DOM与BOM部分示例
    伪类与伪元素
    第三次随笔(按钮外观改变)
  • 原文地址:https://www.cnblogs.com/Mangata/p/14287581.html
Copyright © 2011-2022 走看看