E - 内存管理
Time
Limit:1000MS Memory
Limit:32768KB 64bit
IO Format:%I64d & %I64u
Description
2
Create 1 30
Create 2 20
Create 3 30
Create 4 100
Delete 4
Delete 2
Delete 3
End
Create 1 100
End
Sample
Output
Create process 1 of size 30 successfully!
Create process 2 of size 20 successfully!
Create process 3 of size 30 successfully!
P 1 30
P 2 20
P 3 30
H 20
No enough memory!
No such process!
Delete process 2 of size 20 successfully!
P 1 30
H 20
P 3 30
H 20
Delete process 3 of size 30 successfully!
P 1 30
H 70
Create process 1 of size 100 successfully!
P 1 100
其实这道题就根据题目意思一步一步来写就可以了,简单是简单,但是很烦,细节要注意,尤其是关于头和尾的操作要单独算,也不要忘记把相邻的空内存合并,发现很多人都用链表写的,表示还没学哇,就用vector写了一个,应该还是很好理解的。
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
char str[100];
int arr[105];
struct node
{
int id;
char state;
int size;
};
vector<node> G;
int main()
{
int t, tmp, msize, flag, a, j;
scanf("%d", &t);
while(t--)
{
node in;
in.id = 0;
in.state = 'H';
in.size = 100;
G.push_back(in);
while(~scanf("%s", str))
{
if(strcmp(str, "End") == 0) break;
if(strcmp(str, "Create") == 0)
{
scanf("%d%d", &in.id, &in.size);
tmp = 0, msize = 200;
for(int i = 0; i < G.size(); i++)
{
if(G[i].state == 'H')
{
if(G[i].size >= in.size && G[i].size < msize)
{
msize = G[i].size;
tmp = i;
}
}
}
if(msize == 200) printf("No enough memory!\n");
else
{
in.state = 'P';
G[tmp].size -= in.size;
G.insert(G.begin()+tmp, in);
if(G[tmp].size == 0)
{
G.erase(G.begin() + tmp);
}
printf("Create process %d of size %d successfully!\n", in.id, in.size);
}
}
if(strcmp(str, "Print") == 0)
{
for(int i = 0; i < G.size(); i++)
{
if(G[i].state == 'P')
printf("%c %d %d\n", G[i].state, G[i].id, G[i].size);
else
if(G[i].size != 0)
printf("H %d\n", G[i].size);
}
}
if(str[0] == 'D')
{
flag = 1;
scanf("%d", &a);
for(j = 0; j < G.size(); j++)
{
if(G[j].id == a && G[j].state == 'P')
{
printf("Delete process %d of size %d successfully!\n", a, G[j].size);
a = 0;
G[j].state = 'H';
if(j == 0)
{
if(G[1].state == 'H')
{
G[0].size += G[1].size;
G.erase(G.begin() + 1);
}
}
else
{
if(j == G.size())
{
if(G[j-1].state == 'H')
{
G[j-1].size += G[j].size;
G.erase(G.begin() + j);
}
}
else
{
if(G.size() > 1)
{
if(G[j-1].state == 'H')
{
G[j].size += G[j-1].size;
G.erase(G.begin()+j-1);
flag = 0;
}
if(G[j+flag].state == 'H')
{
G[j+flag-1].size += G[j+flag].size;
G.erase(G.begin()+j+flag);
}
}
break;
}
}
}
}
if(a != 0) printf("No such process!\n");
}
}
G.clear();
}
return 0;
}