class MemoryPool:
def __init__(self, total_size=100):
self.total_size = total_size
self.memory = [None] * total_size # 用列表模拟内存池
self.allocated = {} # 记录已分配的内存块 {起始地址: 大小}
def request(self, size):
if size <= 0 or size> self.total_size:
return "error"
# 寻找连续空闲内存
start = 0
while start < self.total_size:
if self.memory[start] is None:
end = start
while end < self.total_size and self.memory[end] is None:
if end - start + 1 == size:
# 分配内存
for i in range(start, end + 1):
self.memory[i] = "allocated"
self.allocated[start] = size
return start
end += 1
start = end + 1
else:
start += 1
return "error"
def release(self, address):
if address not in self.allocated:
return "error"
# 释放内存
size = self.allocated[address]
for i in range(address, address + size):
self.memory[i] = None
del self.allocated[address]
return None
# 处理输入
def process_commands(commands):
memory_pool = MemoryPool()
for cmd in commands:
if cmd.startswith("REQUEST="):
size = int(cmd.split("=")[1])
result = memory_pool.request(size)
if result is not None:
print(result)
elif cmd.startswith("RELEASE="):
address = int(cmd.split("=")[1])
result = memory_pool.release(address)
if result == "error":
print("error")
else:
print("error")
# 输入处理
N = int(input("请输入操作命令的个数: "))
commands = [input(f"请输入第 {i + 1} 个操作命令: ") for i in range(N)]
# 执行命令
process_commands(commands)