fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. using namespace std;
  6.  
  7. class Cache {
  8. private:
  9. vector<pair<int, int>> memory; // pair<value, index>
  10. const int MAX_SIZE = 20;
  11.  
  12. public:
  13. void add(int number, int index) {
  14. if (memory.size() >= MAX_SIZE) {
  15. memory.erase(memory.begin());
  16. }
  17. memory.push_back({number, index});
  18. }
  19.  
  20. bool checkCache(int index, int& number) {
  21. for (const auto& entry : memory) {
  22. if (entry.second == index) {
  23. number = entry.first;
  24. return true;
  25. }
  26. }
  27. return false;
  28. }
  29. };
  30.  
  31. int main() {
  32. Cache cache;
  33. map<int, int> mainMemory;
  34. string word;
  35.  
  36. // خواندن حافظه اصلی
  37. while (cin >> word) {
  38. if (word == "end") break;
  39. int number = stoi(word);
  40. int index;
  41. if (!(cin >> index)) {
  42. cerr << "Invalid input for index.\n";
  43. return 1;
  44. }
  45. mainMemory[index] = number;
  46. }
  47.  
  48. // پردازش درخواست‌ها
  49. while (cin >> word) {
  50. if (word == "end") break;
  51. if (word == "give") {
  52. int index;
  53. if (!(cin >> index)) {
  54. cerr << "Invalid input for give index.\n";
  55. return 1;
  56. }
  57. int number;
  58. if (cache.checkCache(index, number)) {
  59. cout << "hit with " << number << endl;
  60. } else {
  61. if (mainMemory.find(index) != mainMemory.end()) {
  62. number = mainMemory[index];
  63. cache.add(number, index);
  64. cout << "miss with " << number << endl;
  65. } else {
  66. cout << "miss with 0" << endl;
  67. }
  68. }
  69. }
  70. }
  71.  
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0.01s 5320KB
stdin
254458 125631
158434 135979
375828 202137
end
give 125631
give 135979
give 202137
give 125631
end
stdout
miss with 254458
miss with 158434
miss with 375828
hit with 254458