國標 19266:五常大米稻花香 2 號 10 斤 45.9 元(立減 30 元)
阿新 • • 發佈:2022-02-05
思路:定義全域性變數陣列儲存,通過map對映。
#include <iostream> #include <string> #include <map> using namespace std; class MiniMemoryPool { private: int total[100] = {0}; int totalmem = 100; map<int, int> mem; public: bool isempty(int s, int size) { for (int i = 0; i < size; i++) {以大多數人努力程度之低,根本輪不到去拼天賦~if (total[s + i]) { return false; } } return true; } // 返回分配的記憶體首地址,失敗返回 -1 int Request(int size) { if (size == 0 || size > totalmem) { return -1; } else { for (int i = 0; i < 100; i++) {if (isempty(i, size)) { totalmem -= size; mem[i] = size; for(int k = 0; k < size;k++) { total[k+i] = 1; } return i; } } }return -1; } // 釋放記憶體地址, 成功返回 true, 失敗返回 false bool Release(int startAddr) { if (mem[startAddr]) { totalmem += mem[startAddr]; for (int i = 0; i < mem[startAddr]; i++) { total[i + startAddr] = 0; } mem.erase(startAddr); return true; } return false; } }; int main() { int num; cin >> num; MiniMemoryPool pool; for (int loop = 0; loop < num; loop++) { string line; cin >> line; string commond = line.substr(0, line.find_first_of('=')); if (commond == "REQUEST") { int size = stoi(line.substr(line.find_first_of('=')+1)); int result = pool.Request(size); if (result != -1) { cout << result << endl; } else { cout << "error" << endl; } } else if (commond == "RELEASE") { int addr = stoi(line.substr(line.find_first_of('=')+1)); if (!pool.Release(addr)) { cout << "error" << endl; } } } return 0; }