题目

浏览器有一个cache,可以存放M(M <= 5000) 个url地址(url为长度小于30的字符串)。现在进行N(N <= 20000)次访问,每一个访问,如果访问的url在cache中存在,则输出Cache,如果不在cache中存在,输出Internet,且从cache中删除一个最近最少访问的url,然后将该新访问的url添加到cache中。

分析

LRU cache类似的题目,维持一个unordered_map记录< url, iterator in cache list>,以及一个 list< string> 用作cache(因为list相比较vector,deque,queue等容器,它从中间删除一个元素的时间复杂度为O(1)). 
    如果url在< url, iterator in list>中存在,则将url在list中的节点提前到list的头部,并更新 < url, iterator in list>;     如果url在容器中不存在,(1)如果unordered_map< url, iterator in list>的大小为M,则需要删除list中尾部的url,同时将 unordered_map< url, iterator in list>中对应的项一块删除。(2)如果unordered_map< url, iterator in list>的大小小于M,则直接加入list头部,并设置unordered_map< url, iterator in list>

实现

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<unordered_map>
#include<list>
#include<string>
#include<set>
using namespace std;
list<string> cache;
unordered_map<string, list<string>::iterator> str_it_map;
int main(){
int n, m;
char url[50];
scanf("%d %d", &n, &m);
getchar();
for (int i = 0; i < n; i++){
scanf("%s", url);
if (str_it_map.find(url) == str_it_map.end()){
if (str_it_map.size() == m){
str_it_map.erase(*(--cache.end()));
cache.erase(--cache.end());
}
cache.push_front(url);
str_it_map[url] = cache.begin();
printf("Internet\n");
}
else{
cache.erase(str_it_map[url]);
cache.push_front(url);
str_it_map[url] = cache.begin();
printf("Cache\n");
} }
return 0;
}

hiho_1086_browser_caching的更多相关文章

随机推荐

  1. isp和3a的联系与区别是什么?

    Willis Zen上善若水 2 人赞同 你说的这个问题,不是很多人能够回答的,我也只能把我知道的告诉你.isp 是image signal processing,用于图像处理,比如gamma调整,d ...

  2. 华东交通大学2016年ACM“双基”程序设计竞赛 1002

    Problem Description 今天小学弟又训练完了,但是小学弟又不想看球赛,于是小学弟看马赛了.他发现马鞍是一个奇怪的东西.于是小学弟根据马鞍定义了一种马鞍数:在一个二位矩阵中,马鞍数在当前 ...

  3. 2016年11月1日 星期二 --出埃及记 Exodus 19:17

    2016年11月1日 星期二 --出埃及记 Exodus 19:17 Then Moses led the people out of the camp to meet with God, and t ...

  4. linux下如何安装配置redis及主从配置

    redis的优点:支持主从备份,操作指令丰富,支持异步的数据持久化 将 redis 安装到 /usr/local/webserver/redis 1.下载安装包 wget http://redis.g ...

  5. Duilib自定义控件响应指定命令(转载)

    转载:http://blog.csdn.net/panxianzhan/article/details/50772893 duilib在UIManager.h里的EVENTTYPE_UI枚举里定义了很 ...

  6. CodeForces 670D2 Magic Powder 二分

    D2. Magic Powder - 2 The term of this problem is the same as the previous one, the only exception — ...

  7. vs2012 提示 未能正确加载 "Visual C++ Language Manager Package" 包 的解决办法

    1.点击vs2012菜单栏 工具-> Visual Studio 命令提示 打开命令窗口 2.输入命令 "devenv /Setup" 3.重新打开vs2012

  8. 后台输出HTML

    在前台定义CSS样式: <style type="text/css"> .style1 { width: 120px; } .style3 { width: 488px ...

  9. cdoj 851 方老师与素数 bfs

    方老师与素数 Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit St ...

  10. HTML笔记(四) 框架

    通过框架,可以在一个窗口显示多个页面.而所谓的框架,就是指每一份HTML文档. 框架结构标签<frameset> 定义如何将窗口分割为框架. frameset定义了一系列的行列. rows ...