C++解法
1.简易内存池:
内存池总大小为从低到高连续分配的100字节,有REQUEST和QELEASE两种请求,分别放进某大小的内存或释放某大小的内存,格式为REQUEST=20或QELEASE=0,如果释放不存在的首地址或存入内存大小为0,则输出error,如果成功释放内存则无需输出。
例:
输入:
7
REQUEST=10
REQUEST=20
RELEASE=0
REQUEST=0
REQUEST=20
RELEASE=15
REQUEST=10
输出:
0
10
error
30
error
0
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
using namespace std;
int FindPos(map<int, int>& memory, int size) {
int count = 0, pos = -1;
for (int i = 0; i < 100; i++) {
if (memory[i] == 0) {
count++;
if (pos == -1) { pos = i; }
if (count == size) { break; }
}
else {
count = 0;
pos = -1;
}
}
if (count != size) { return -1; }
return pos;
}
int main() {
int n;
cin >> n;
vector<string> quest;
while (n > 0) {
string input, tmp;
cin >> input;
istringstream istst(input);
while (getline(istst, tmp, '='))
quest.push_back(tmp);
n--;
}
map<int, int> memory;
for (int i = 0; i < quest.size(); i += 2) {
if (quest[i] == "REQUEST") {
int size = stoi(quest[i + 1]);
if (size == 0) { cout << "error" << endl; continue; }
else {
int pos = FindPos(memory, size);
if (pos == -1) { cout << -1 << endl; continue; }
else {
cout << pos << endl;
for (int j = pos; j < pos + size; j++) {
memory[j] = 1;
if (j == pos) { memory[j] = 2; }
if (j == pos + size - 1) { memory[j] = 3; }
}
}
}
}
else {
int size = stoi(quest[i + 1]);
if (memory[size] != 2) { cout << "error" << endl; continue; }
else {
for (int j = size; j < 100; j++) {
if (memory[j] == 3) { memory[j] = 0; break; }
memory[j] = 0;
}
}
}
}
}