題意
模擬LRU算法
- 操作1:cache中查詢中是否有sss,并讀出index+vindex+vindex+v的data
- 操作0:cache中插入sss,sss存在輸出datadatadata并移動到末尾,sss不存在插入到末尾
插入操作用cachecachecache的容量大于mmm彈出第一個datadatadata
思路
一直沒用過CCC++的listlistlist,這個題用 listlistlist超級好寫。
- listlistlist是一種類似vectorvectorvector的容器,支持pushback、pushfront、clear、erasepush_back、push_front、clear、erasepushb?ack、pushf?ront、clear、erase等操作,還有一點特別好,迭代器刪除某個容器,剩下的元素的迭代器不影響,所以插入的時候記錄下每個元素的iteratoriteratoriterator,需要查詢的時候直接拿出來訪問就行。
- unorder_map底層哈希表查詢效率高
list
<string
> test
;map
<string
, list
<string
>::iterator
> mp
;test
.push_back("a");test
.push_front("b");test
.push_front("c");test
.push_back("d");for (auto it
: test
) {cout
<< it
<< endl
;}cout
<< endl
;auto it
= test
.begin();while (it
!= test
.end()) {mp
[*it
] = it
;++it
;} test
.erase(mp
["a"]);cout
<< *mp
["b"] << " " << *mp
["d"] << endl
;
#include <bits/stdc++.h>
#define psi pair<string,int>
#define endl "\n"
const int maxn
= 1e5 + 5;
const int inf
= 0x3f3f3f3f;
using namespace std
;
int n
, m
, op
, T
, v
, t
;
string s
;
list
<psi
> LRU
;
unordered_map
<string
, list
<psi
>::iterator
> mp
;
void add() {if (mp
.find(s
) != mp
.end()) {auto it
= mp
[s
];cout
<< it
->second
<< endl
;LRU
.push_front(*it
);mp
[s
] = LRU
.begin();LRU
.erase(it
);}else {cout
<< v
<< endl
;if (t
== m
) {auto it
= LRU
.end();--it
;LRU
.pop_back();mp
.erase(it
->first
);t
--;}LRU
.push_front(make_pair(s
, v
));mp
[s
] = LRU
.begin();t
++;}
}
void search() {if (mp
.find(s
) == mp
.end()) {cout
<< "Invalid\n";return;}auto it
= mp
[s
];if (v
== 0) {cout
<< it
->second
<< endl
;}if (v
== 1) {if (it
== LRU
.begin()) cout
<< "Invalid\n";else cout
<< (--it
)->second
<< endl
;}if (v
== -1) {++it
;if (it
== LRU
.end()) cout
<< "Invalid\n";else cout
<< it
->second
<< endl
;}
}
int main() {ios
::sync_with_stdio(false);cin
.tie(0), cout
.tie(0);cin
>> T
;while (T
--) {LRU
.clear();mp
.clear();t
= 0;cin
>> n
>> m
;for (int i
= 0; i
< n
; ++i
) {cin
>> op
>> s
>> v
;op
? search() : add();} }return 0;
}
總結
以上是生活随笔為你收集整理的2019牛客暑期多校训练营(第三场)J - LRU management (模拟+list+unorder_map)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。