菜鸡的代码,还有很多可以简化的地方,只是笔试没时间优化,现在也懒得优化,便作罢,就照搬了上来,请大佬指正
手写到自闭。。
示例代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct graph
{
char type[10];
int *start;
int used[2000];
int state;
int real_size;
};
struct graph *configMemory(int size);
int * getMemory(int size, struct graph *graphs);
void freeMemory(int *ptr, struct graph *graphs);
void random(int num, struct graph *graphs);
struct graph *configMemory(int size)
{
int i, j;
int *pool = (int *)malloc(sizeof(int) * size);
struct graph *graphs = (struct graph *)malloc(sizeof(struct graph) * 3);
int small, mid, big;
small = size / 3 / 50;
mid = size / 3 / 100;
big = size / 3 / 200;
strcpy(graphs[0].type, "small");
strcpy(graphs[1].type, "mid");
strcpy(graphs[2].type, "big");
graphs[0].start = pool;
graphs[1].start = pool + small * 50;
graphs[2].start = pool + mid * 100;
for (i = 0; i < 2000; i++)
{
for (j = 0; j < 3; j++)
{
graphs[j].used[i] = 0;
}
}
graphs[0].state = 0;
graphs[1].state = 0;
graphs[2].state = 0;
graphs[0].real_size = small * 50;
graphs[1].real_size = mid * 100;
graphs[2].real_size = big * 200;
return graphs;
}
int * getMemory(int size, struct graph *graphs)
{
if (size <= 50)
{
if (graphs[0].state * 50 < graphs[0].real_size)
{
for (int i = 0; i < graphs[0].real_size / 50; i++)
{
if (graphs[0].used[i] == 0)
{
graphs[0].used[i] = 1;
graphs[0].state++;
return graphs[0].start + i * 50;
}
}
}
else
{
return NULL;
}
}
else if (size <= 100)
{
if (graphs[1].state * 100 < graphs[1].real_size)
{
for (int i = 0; i < graphs[1].real_size / 100; i++)
{
if (graphs[1].used[i] == 0)
{
graphs[1].used[i] = 1;
graphs[1].state++;
return graphs[1].start + i * 100;
}
}
}
else
{
return NULL;
}
}
else if (size <= 200)
{
if (graphs[2].state * 200 < graphs[2].real_size)
{
for (int i = 0; i < graphs[2].real_size / 200; i++)
{
if (graphs[2].used[i] == 0)
{
graphs[2].used[i] = 1;
graphs[2].state++;
return graphs[2].start + i * 200;
}
}
}
else
{
return NULL;
}
}
}
void freeMemory(int *ptr, struct graph *graphs)
{
if (ptr < graphs[1].start)
{
graphs[0].state--;
graphs[0].used[(ptr - graphs[0].start) / 50] = 0;
}
else if (ptr < graphs[2].start)
{
graphs[1].state--;
graphs[1].used[(ptr - graphs[1].start) / 100] = 0;
}
else
{
graphs[2].state--;
graphs[2].used[(ptr - graphs[2].start) / 200] = 0;
}
}
void random(int num, struct graph *graphs)
{
int i;
int *used = (int *)malloc(sizeof(int) * num);
for (i = 0; i < num; i++)
{
used[i] = 0;
}
int **ptr = (int **)malloc(sizeof(int*) * num);
for (i = 0; i < num; i++)
{
int size = rand() % 150 + 51;
int *p = getMemory(size, graphs);
if (p)
{
printf("%d %d %p\n", i + 1, size, p);
used[i] = 1;
ptr[i] = p;
}
else
{
printf("%d %d NULL\n", i + 1, size);
}
}
for (i = 0; i < num; i++)
{
if (used[i])
{
freeMemory(ptr[i], graphs);
}
}
}
int main()
{
int size;
scanf("%d", &size);
struct graph *graphs = configMemory(size);
int num;
scanf("%d", &num);
random(num, graphs);
system("pause");
return 0;
}