这题本来以为不容易,觉得很容易会TLE,可后来发觉其实复杂度也不高,因为表项不超过100,所以可以放心地疯狂地遍历。。。
debug了很久,一堆小错误。。。
AC CODE(编得不好)
//Memory: 240 KB Time: 0 MS
//Language: GNU C++ Result: Accepted
#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
struct Node
{
int size; //记录这块内存空间的大小
bool used; //标记这块内存是否被占用
int idx; //这块内存的编号
int id; //占用这块内存区域的是编号为idx的进程
Node *next;
Node *pre;
}dum, m[300];
char str[7];
int i, s, T, k;
int p[1001]; //两个功能:1.储存进程所在表项编号,2.q[i]为-1时表明进程不存在
void Init()
{
dum.pre = NULL;
dum.size = 0;
for(int j = 0; j < 300; j++)
{
m[j].pre = m[j].next = NULL;
m[j].used = false;
m[j].size = 0;
m[j].idx = j;
}
m[0].size = 100;
dum.next = &m[0];
m[0].pre = &dum;
memset(p, -1, sizeof(p));
k = 1;
}
int main()
{
Init();
scanf("%d",&T);
while(1)
{
scanf("%s", str);
//CREAT
if(str[0] == 'C')
{
scanf("%d%d", &i, &s);
int minsize = 101; //用大小为minsize的内存区域储存新进程
int minidx; //内存的编号
for(struct Node *h = dum.next; h != NULL; h = h ->next)
{
if(!h ->used && h ->size >= s && h ->size < minsize)
{
minsize = h ->size;
minidx = h ->idx;
}
}
if(minsize == 101)
{
puts("No enough memory!");
continue;
}
printf("Create process %d of size %d successfully!\n", i, s);
m[minidx].used = true;
m[minidx].id = i;
if(minsize != s) //有多余空间时才创建空表项
{
m[k].size = minsize - s;
m[k].pre = &m[minidx];
m[k].next = m[minidx].next;
m[minidx].next = &m[k];
k++;
}
m[minidx].size = s;
p[i] = minidx; //记录编号为i的进程储存在哪一个内存区域
}
//DELETE
else if(str[0] == 'D')
{
scanf("%d", &i);
if(p[i] < 0)
{
puts("No such process!");
continue;
}
int t = p[i]; //获取要删除的进程所在的内存编号
printf("Delete process %d of size %d successfully!\n", i, m[t].size);
p[i] = -1; //重设为-1,表明这个进程已经被删除
m[t].used = false; //重新标记为未使用
if(!(m[t].pre ->used) && m[t].pre != &dum) //上一表项空闲,则合并
{
m[t].size += m[t].pre ->size;
m[t].pre ->size = 0;
m[t].pre ->pre ->next = &m[t];
m[t].pre = m[t].pre ->pre;
}
if(m[t].next != NULL && !(m[t].next ->used)) //下一表项空闲,则合并
{
m[t].size += m[t].next ->size;
m[t].next ->size = 0;
if(m[t].next ->next != NULL)
m[t].next ->next ->pre = &m[t];
m[t].next = m[t].next ->next;
}
}
else if(str[0] == 'P')
{
for(struct Node *h = dum.next; h != NULL; h = h ->next)
{
if(h ->used)
printf("P %d %d\n", h ->id, h ->size);
else
printf("H %d\n", h ->size);
}
}
else
{
T--;
if(!T) break;
Init();
}
}
return 0;
}