第1484题,Allocation of Memory,题目链接http://202.197.224.59/OnlineJudge/index.php/problem/read/id/1484,直接暴力模拟。收到Quit信号,即清空内存为0。否则,察看如果有空间,若有,直接使用,赋值为pid,输出内存地址;否则,碎片整理,再看是否有空间,若有,直接使用,赋值为pid,输出内存地址;若无,输出-1。
C语言代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_MEMORY 510
typedef int COUNT;
int memory[MAX_MEMORY];
int maxMemory;
bool canAlloc( int start, int apply )
{
COUNT i;
for ( i = 0 ; i < apply ; i ++ )
{
if ( start + i > maxMemory )
return false;
if ( memory[start+i] != 0 )
return false;
}
return true;
}
void defrag(void)
{
COUNT i, j;
for ( i = 1 ; i <= maxMemory ; i ++ )
{
if ( memory[i] == 0 )
{
for ( j = i + 1 ; j <= maxMemory ; j ++ )
{
if ( memory[j] != 0 )
{
memory[i] = memory[j];
memory[j] = 0;
break;
}
}
}
}
}
int alloc( int pid, int apply )
{
COUNT i, j;
for ( i = 1 ; i <= maxMemory ; i ++ )
{
if ( memory[i] == 0 )
{
if ( canAlloc(i, apply) )
{
for ( j = 0 ; j < apply ; j ++ )
memory[i+j] = pid;
return i;
}
}
}
defrag();
for ( i = 1 ; i <= maxMemory ; i ++ )
{
if ( memory[i] == 0 )
{
if ( canAlloc(i, apply) )
{
for ( j = 0 ; j < apply ; j ++ )
memory[i+j] = pid;
return i;
}
}
}
return -1;
}
void killprocess( int pid )
{
COUNT i;
for ( i = 1; i <= maxMemory ; i ++ )
{
if ( memory[i] == pid )
memory[i] = 0;
}
}
int main (void)
{
int testcases;
COUNT i, j;
char cmd[12];
int pid, apply;
int instructions;
scanf( "%d", &testcases );
for ( i = 1 ; i <= testcases ; i ++ )
{
scanf( "%d%d", &maxMemory, &instructions );
memset( memory, 0, sizeof(memory) );
printf( "Case %d:\n", i );
for ( j = 0 ; j < instructions ; j ++ )
{
scanf( "%s", cmd );
if ( !strcmp( cmd, "New" ) )
{
scanf( "%d%d", &pid, &apply );
printf( "%d\n", alloc( pid, apply ) );
}
else
{
scanf( "%d", &pid );
killprocess( pid );
}
}
}
return EXIT_SUCCESS;
}