CodeForce 7 B - Memory Manager(模拟)

题目大意:给你一段内存,要你进行如下的三个操作。

1.分配内存  alloc   X ,分配连续一段长度为X的内存。
如果内存不够应该输出NULL,如果内存够就给这段内存标记一个编号。
2.擦除编号为 X的内存,erase X,  如果这段内存不存在那么输出“ILLEGAL_ERASE_ARGUMENT ”,否则什么都不输出。
3.整理内存,把所有的内存块整理到一块。
 
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
using namespace std;
typedef long long LL;
const int INF = 1e9+7;
const int maxn = 1055;

int Arr[maxn];
int n, m, a, ans;
int Blocks = 0;
char op[50];

int Alloc(int a)
{
    for(int i=1; i<=m; i++)
    {
        int j = i, num = 0;
        while(Arr[j] == 0 && num != a && j <= m)
            num ++, j ++;
        if(num != a)
            i = j;
        else
        {
            Blocks ++;
            for(int k=i; k<j; k++)
                Arr[k] = Blocks;
            return Blocks;
        }
    }
    return 0;
}

int Erase(int Id)
{
    if(Id <= 0)
        return -1;
    bool flag = false;
    for(int i=1; i<=m; i++)
    {
        while(Arr[i] == Id)
            Arr[i++] = 0, flag = true;
    }
    if(flag)
        return -2;
    return -1;
}

int Defragment()
{
    for(int i=1; i<=m; i++)
    {
        if(Arr[i] == 0)
        {
            for(int j=i+1; j<=m; j++)
            {
                if(Arr[j])
                {
                    swap(Arr[i], Arr[j]);
                    break;
                }

            }
        }
    }
    return -5;
}


int main()
{

    scanf("%d %d", &n, &m);
    memset(Arr, 0, sizeof(Arr));
    while(n --)
    {
        scanf("%s", op);
        if(strcmp(op, "alloc") == 0)
        {
            scanf("%d", &a);
            ans = Alloc(a);
        }
        else if( strcmp(op, "erase") == 0 )
        {
            scanf("%d", &a);
            ans = Erase(a);
        }
        else
            ans = Defragment();

        if( ans == 0)
            puts("NULL");
        else if(ans == -1)
            puts("ILLEGAL_ERASE_ARGUMENT");
        else if(ans >= 1)
            printf("%d\n", ans);

    }


    return 0;
}

 

posted @ 2015-10-23 17:10  向前走丶不回首  阅读(155)  评论(0编辑  收藏  举报