题目

浏览器有一个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. Uva 11584,划分成回文串

    题目链接:https://uva.onlinejudge.org/external/115/11584.pdf 题意: 一个字符串,将它划分一下,使得每个串都是回文串,求最少的回文串个数. 分析: d ...

  2. MySQL日期时间函数大全

    DAYOFWEEK(date) 返回日期date是星期几(=星期六,ODBC标准) mysql> select DAYOFWEEK('1998-02-03'); WEEKDAY(date) 返回 ...

  3. hdu敌兵布阵

    http://acm.hdu.edu.cn/showproblem.php?pid=1166 敌兵布阵 Time Limit: 2000/1000 MS (Java/Others)    Memory ...

  4. java实现多线程断点续传,上传下载

    采用apache 的 commons-net-ftp-ftpclient import java.io.File; import java.io.FileOutputStream; import ja ...

  5. dubbo源码之四——服务发布二

    dubbo版本:2.5.4 2. 服务提供者暴露一个服务的详细过程 上图是服务提供者暴露服务的主过程: 首先ServiceConfig类拿到对外提供服务的实际类ref(如:HelloWorldImpl ...

  6. QT笔记之模态对话框及非模态对话框

    模态对话框(Modal Dialog)与非模态对话框(Modeless Dialog)的概念不是Qt所独有的,在各种不同的平台下都存在.又有叫法是称为模式对话框,无模式对话框等.所谓模态对话框就是在其 ...

  7. JDBC批量处理

    转载自http://www.cnblogs.com/xdp-gacl/p/3983253.html 在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而 ...

  8. FZU 2151 OOXX Game

    OOXX Game Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit St ...

  9. ubuntu下chromium 安装flash player

    原文地址 :http://blog.sina.com.cn/s/blog_858820890102v63w.html 不记得从什么时候起,Chromium 不再支持 Netscape plugin A ...

  10. django-crontab定时任务

    django-crontab实现定时任务 1 django-crontab安装 django-crontab安装: django-crontab加入:只需要将INSTALLED_APPS即可.如下代码 ...