-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru.cpp
More file actions
61 lines (49 loc) · 1.31 KB
/
lru.cpp
File metadata and controls
61 lines (49 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <exception>
#include <stdexcept>
#include <iostream>
#include <iterator>
#include <list>
#include <unordered_map>
template <typename T, typename KeyT = int>
class cache_t {
public:
size_t sz_;
std::list<T> cache_;
typedef typename std::list<T>::iterator ListIt;
std::unordered_map<int, ListIt> hash_;
bool full() const {
return (cache_.size() == sz_);
}
bool lookup(int elem) {
auto hit = hash_.find(elem);
if (hit == hash_.end()) {
if (full()) {
hash_.erase(cache_.back());
cache_.pop_back();
}
cache_.push_front(elem);
hash_[elem] = cache_.begin();
return false;
}
auto eltit = hit->second;
if (eltit != cache_.begin())
cache_.splice(cache_.begin(), cache_, eltit, std::next(eltit));
return true;
}
};
int main() {
int hits = 0;
int n, m;
std::cin >> m >> n;
cache_t<int> c{static_cast<size_t>((m))};
for (int i = 0; i < n; ++i) {
int q;
std::cin >> q;
if ( std::cin.good () == false) {
throw std::runtime_error("ERROR");
}
if (c.lookup(q))
hits += 1;
}
std::cout << hits << std::endl;
}