#include <iostream>
#include <vector>
using namespace std;

const int MAX_MEM_SIZE = 100;
const int MAX_JOB_NAME_LENGTH = 20;

int mem_state[MAX_MEM_SIZE][2];
vector<int> job_blocks[MAX_JOB_NAME_LENGTH];
int job_count = 0;
char job_name[MAX_JOB_NAME_LENGTH];

// 初始化内存空间
void initMem() {
cout << "请输入内存空间各个物理块状态（1代表已分配，0代表未分配）：" << endl;
for (int i = 0; i < MAX_MEM_SIZE; i++) {
cin >> mem_state[i][0];
mem_state[i][1] = i;
}
// 显示初始化后的内存状态
cout << "内存分配情况：" << endl;
for (int i = 0; i < MAX_MEM_SIZE; i++) {
cout << mem_state[i][0] << " ";
if (i % 10 == 9) cout << endl;
}
}

// 分配作业空间
void allocateJob() {
//char job_name[MAX_JOB_NAME_LENGTH];
int job_size = 0;
cout << "请输入要分配的作业名和大小（单位为逻辑页面数）：" << endl;
cin >> job_name >> job_size;
// 判断作业名是否已存在
bool exists = false;
for (int i = 0; i < job_count; i++) {
if (strcmp(job_name, to_string(i).c_str()) == 0) {
cout << "作业名已存在，请换一个名字。" << endl;
exists = true;
break;
}
}
if (exists) return;
// 查找连续的空闲物理块
int start = -1, count = 0;
for (int i = 0; i < MAX_MEM_SIZE; i++) {
if (mem_state[i][0] == 0) {
if (start == -1) start = i;
count++;
} else {
start = -1;
count = 0;
}
if (count >= job_size) break;
}
// 判断是否有足够的连续空闲物理块
if (count < job_size) {
cout << "内存不足，分配失败。" << endl;
return;
}
// 记录分配的物理块列表
for (int i = start; i < start+job_size; i++) {
job_blocks[job_count].push_back(mem_state[i][1]);
mem_state[i][0] = 1;
}
// 输出分配结果
cout << "作业 " << job_name << " 分配成功：" << endl;
cout << "分配的物理块号为：";
for (int i = 0; i < job_blocks[job_count].size(); i++) {
cout << job_blocks[job_count][i] << " ";
}
cout << endl;
job_count++;
}

// 回收作业空间
void deallocateJob() {
//char job_name[MAX_JOB_NAME_LENGTH];
cout << "请输入要回收的作业名：" << endl;
cin >> job_name;
// 查找作业占用的物理块列表
int job_index = -1;
for (int i = 0; i < job_count; i++) {
if (strcmp(job_name, to_string(i).c_str()) == 0) {
job_index = i;
break;
}
}
if (job_index == -1) {
cout << "作业不存在，回收失败。" << endl;
return;
}
// 回收物理块
for (int i = 0; i < job_blocks[job_index].size(); i++) {
int block_number = job_blocks[job_index][i];
mem_state[block_number][0] = 0;
}
// 清空作业占用的物理块列表
job_blocks[job_index].clear();
// 输出回收结果
cout << "作业 " << job_name << " 回收成功。" << endl;
}

// 显示内存状态
void showMem() {
cout << "当前内存情况：" << endl;
cout << "物理块号 状态" << endl;
for (int i = 0; i < MAX_MEM_SIZE; i++) {
cout << mem_state[i][1] << " " << mem_state[i][0] << endl;
}
}

//例子：
/*
1 0 0 1 1 0 0 0 1 1
0 0 1 1 1 0 0 0 1 1
0 0 1 0 0 0 1 1 1 1
1 0 1 0 1 0 0 1 0 1
1 1 1 0 0 0 0 1 1 0
1 1 0 1 1 0 1 1 0 1
1 0 0 0 1 1 0 0 0 0
1 1 0 1 0 1 1 0 0 1
0 0 0 1 1 1 0 1 0 1
0 1 0 1 1 1 0 1 1 1
*/
int main() {
initMem();
while (true) {
cout << "请选择操作：" << endl;
cout << "1. 分配作业空间" << endl;
cout << "2. 回收作业空间" << endl;
cout << "3. 显示内存状态" << endl;
cout << "4. 退出程序" << endl;
int choice = 0;
cin >> choice;
switch (choice) {
case 1:
allocateJob();
break;
case 2:
deallocateJob();
break;
case 3:
showMem();
break;
case 4:
return 0;
default:
cout << "无效的操作，请重新选择。" << endl;
break;
}
}
}