fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <sstream>
  5. using namespace std;
  6.  
  7. int main() {
  8. vector<int> mainNumbers;
  9. vector<int> mainIndexes;
  10.  
  11. vector<int> cacheNumbers;
  12. vector<int> cacheIndexes;
  13.  
  14. string line;
  15.  
  16. // خواندن حافظه اصلی
  17. while (getline(cin, line)) {
  18. if (line == "end") break;
  19. if (line.empty()) continue;
  20.  
  21. stringstream ss(line);
  22. int num, idx;
  23. ss >> num >> idx;
  24. mainNumbers.push_back(num);
  25. mainIndexes.push_back(idx);
  26. }
  27.  
  28. // خواندن دستورات give
  29. while (getline(cin, line)) {
  30. if (line == "end") break;
  31. if (line.empty()) continue;
  32.  
  33. stringstream ss(line);
  34. string cmd;
  35. int idx;
  36. ss >> cmd >> idx;
  37. if (cmd != "give") continue;
  38.  
  39. // جستجوی جایگاه در کش
  40. bool found = false;
  41. int pos = -1;
  42. for (int i = 0; i < (int)cacheIndexes.size(); i++) {
  43. if (cacheIndexes[i] == idx) {
  44. found = true;
  45. pos = i;
  46. break;
  47. }
  48. }
  49.  
  50. if (found) {
  51. // hit
  52. cout << "hit with " << cacheNumbers[pos] << "\n";
  53. } else {
  54. // miss: پیدا کردن مقدار در حافظه اصلی
  55. int val = -1;
  56. for (int i = 0; i < (int)mainIndexes.size(); i++) {
  57. if (mainIndexes[i] == idx) {
  58. val = mainNumbers[i];
  59. break;
  60. }
  61. }
  62. if (val == -1) {
  63. // اگر جایگاه تو حافظه اصلی نبود، کاری انجام نمیده
  64. continue;
  65. }
  66.  
  67. if ((int)cacheIndexes.size() < 20) {
  68. // اگر کش جا داشت، اضافه کن
  69. cacheIndexes.push_back(idx);
  70. cacheNumbers.push_back(val);
  71. } else {
  72. // کش پر است، حذف اولین ورودی و اضافه کردن ورودی جدید (FIFO)
  73. cacheIndexes.erase(cacheIndexes.begin());
  74. cacheNumbers.erase(cacheNumbers.begin());
  75.  
  76. cacheIndexes.push_back(idx);
  77. cacheNumbers.push_back(val);
  78. }
  79.  
  80. cout << "miss with " << val << "\n";
  81. }
  82. }
  83.  
  84. return 0;
  85. }
  86.  
Success #stdin #stdout 0.01s 5308KB
stdin
254458 125631
158434 135979
165572 260466
155028 101855
194976 189469
233682 146048
149847 323000
175312 275522
261628 305207
363691 318210
375828 202137
345097 203488
113665 234838
165446 320239
272296 316819
112937 245679
106387 200214
255857 242996
113941 257290
207214 174134
205112 310674
114048 115449
235521 392331
298687 153791
209850 239150
171801 335028
356089 393004
251393 161181
265566 236875
220886 228352
355980 217155
399692 128306
163881 278419
397863 155189
328605 269703
291118 388651
301296 275996
end
give 112937
give 265566
give 149847
give 235521
give 375828
give 112937
give 114048
give 375828
give 149847
give 254458
give 251393
give 301296
give 397863
give 291118
give 272296
give 301296
give 205112
give 175312
give 301296
give 165446
give 106387
give 298687
give 345097
give 363691
give 298687
end
stdout
Standard output is empty