forked from codesession/Data-structure-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFU.cc
More file actions
93 lines (88 loc) · 2.15 KB
/
LFU.cc
File metadata and controls
93 lines (88 loc) · 2.15 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <list>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
struct node {
string key;
int fre;
int value;
};
class LFU {
public:
LFU(int size) {
cap = size;
minfre = 100;
};
node* Get(string key) {
if (vnode.find(key) == vnode.end()) {
return nullptr;
}
auto i = vnode[key];
auto fre = (*i)->fre;
auto value = (*i)->value;
fnode[fre].erase(i);
delete *i;
if (fnode[fre].size() == 0 && minfre == fre) {
minfre++;
}
fre++;
node* newnode = new node{key, fre, value};
fnode[fre].push_front(newnode);
return newnode;
};
node* Set(string key, int value) {
if (vnode.size() < cap) {
node* newnode = new node{key, 1, value};
fnode[1].push_front(newnode);
vnode.insert({key, list<node*>::iterator(fnode[1].begin())});
if (minfre > 1) {
minfre = 1;
}
return nullptr;
}
auto i = fnode[minfre].rbegin();
vnode.erase((*i)->key);
fnode[minfre].pop_back();
node* newnode = new node{key, 1, value};
fnode[1].push_front(newnode);
vnode.insert({key, list<node*>::iterator(fnode[1].begin())});
if (minfre > 1) {
minfre = 1;
}
return *i;
};
void Print() {
cout << "print begin" << endl;
for (auto i : fnode) {
cout << "fre:" << i.first << endl;
for (auto j : i.second) {
cout << j->value << " ";
}
cout << endl;
}
cout << endl;
}
private:
unordered_map<string, list<node*>::iterator> vnode;
unordered_map<int, list<node*>> fnode;
int cap;
int minfre;
};
int main() {
LFU foo(3);
foo.Set("hello", 10);
foo.Set("world", 2);
foo.Set("ni", 1);
foo.Set("hao", 33);
foo.Get("ni");
foo.Get("ni");
foo.Set("wo", 123);
foo.Get("wo");
foo.Get("wo");
foo.Get("hao");
foo.Get("hao");
foo.Set("shi", 111);
foo.Print();
};