Allocation of Memory 解题报告

  第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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值