题目描述
解题思路
可以用一个bool数组来模拟内存区,被占用的区域用memset打上标记.
参考代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <map>
const int maxn = 110;
using namespace std;
struct Process{
int begin,size,flag;
}pro[maxn];
bool unit[maxn];
int Find(int size){//找到一段内存大小为size的区域,返回起始地址
int cnt = 0;
for (int i = 1;i <= 100;i++){
for (int j = i;j <= 100;j++){
if (!unit[j]){
cnt++;
if (cnt == size) return i;
}else{
i = j;
cnt = 0;
break;
}
}
cnt = 0;
}
return 0;
}
int main()
{
int T;
scanf("%d",&T);
string opr;
while (T--){
memset(pro,0,sizeof(pro));
memset(unit,false,sizeof(unit));
map<int,int> m;
while (cin >> opr && opr != "End"){
if (opr == "Create"){
int num,size;
scanf("%d %d",&num,&size);
int begin = Find(size);
if (begin){
memset(unit+begin,true,sizeof(bool)*size);
pro[num].flag = 1;
pro[num].begin = begin;
pro[num].size = size;
m[begin] = num;
printf("Create process %d of size %d successfully!\n",num,size);
}else
printf("No enough memory!\n");
}else if (opr == "Delete"){
int num;
scanf("%d",&num);
if (pro[num].flag){
memset(unit+pro[num].begin,false,sizeof(bool)*pro[num].size);
pro[num].flag = 0;
m[pro[num].begin] = 0;
printf("Delete process %d of size %d successfully!\n",num,pro[num].size);
}else
printf("No such process!\n");
}else if (opr == "Print"){
int cnt = 1;
for (int i = 1;i <= 100;i++){
if (m[i]){
int num = m[i],size = pro[m[i]].size;
printf("P %d %d\n",num,size);
i += size-1;
}else{
if (m[i+1] || (!m[i+1] && i == 100)){
printf("H %d\n",cnt);
cnt = 1;
}
else cnt++;
}
}
}
}
}
return 0;
}