您的位置:首页 > 其它

九度OJ 1334:占座位 (模拟)

2015-11-14 21:40 316 查看
时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:864

解决:202

题目描述:

sun所在学校的教室座位每天都是可以预占的。

一个人可以去占多个座位,而且一定是要连续的座位,如果占不到他所要求的这么多座位,那么他就一个座位也不要了。为了降低难度,每次分配座位按座位号从小到大查找,采用最先适配法分配座位。

输入:

输入有多组数据。

每组数据输入座位排数n,0<n<=100(座位的排列数相等,座位是按每行从左到右依次排序的),m( 0<m<=min(100,n*n) )个人。

然后输入k(0<k<=100),最后输入k个命令。

命令只有两种:

1.in id num(代表id,0<=id<m,要占num个座位,若占不到连续的num(0<num<=20)个座位表示该命令无效)

2.out id(代表id要释放他之前占的所有座位)

注意:如果id之前占过座还没释放那么之后他的in命令都是无效的,

如果id之前没占过座位那么他的out命令也是无效的。

输出:

对每个in命令输出yes或者no,如果命令有效则输出yes,无效则输出no。

在yes no后面只带有回车,不带其他任何字符。

样例输入:
4 10
9
in 1 7
in 2 3
in 3 3
in 3 3
in 4 3
out 2
in 5 6
out 3
in 5 6


样例输出:
yes
yes
yes
no
yes
no
yes


思路:

数据结构用了结构体+链表,比较符合这个题的特点。

这个题特别注意两个地方:

如果id之前占过座还没释放那么之后他的in命令都是无效的,

如果id之前没占过座位那么他的out命令也是无效的。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 100

typedef struct node {
int id;
int begin;
int end;
struct node *next;
} Person;

Person *init(Person *head, int n)
{
head = (Person *)malloc(sizeof(Person));
head->id = -1;
head->begin = head->end = 0;
Person *tail = (Person *)malloc(sizeof(Person));
tail->id = tail->begin = tail->end = n+1;
head->next = tail;
tail->next = NULL;
return head;
}

void print(Person *head)
{
while (head)
{
printf("%d %d %d\n", head->id, head->begin, head->end);
head = head->next;
}
}

void insert(Person *head, int id, int num, int m)
{
if (id < 0 || id >= m)
{
printf("no\n");
return;
}

Person *p0, *p;
p0 = head;
p = p0->next;
while (p != NULL)
{
if (p->id == id)
break;
p0 = p;
p = p0->next;
}
if (p != NULL)
{
printf("no\n");
return;
}

p0 = head;
p = p0->next;
while (p != NULL)
{
if (p->id == id)
{
printf("no\n");
return;
}
if (p->begin - p0->end - 1 >= num)
break;
p0 = p;
p = p0->next;
}
if (p == NULL)
{
printf("no\n");
return;
}

Person *pnew = (Person *)malloc(sizeof(Person));
pnew->id = id;
pnew->begin = p0->end + 1;
pnew->end = p0->end + num;
p0->next = pnew;
pnew->next = p;
printf("yes\n");
}

void out(Person *head, int id, int m)
{
if (id < 0 || id >= m)
return;
Person *p0, *p;
p0 = head;
p = p0->next;
while (p != NULL)
{
if (p->id == id)
break;
p0 = p;
p = p0->next;
}
if (p == NULL)
{
return;
}
p0->next = p->next;
free(p);
}

int main()
{
int n, m, k, i;
Person *head;
char op[5];
int id;
int num;

while(scanf("%d%d%d", &n, &m, &k) != EOF)
{
n = n*n;
head = init(head, n);
//print(head);
for (i=0; i<k; i++)
{
scanf("%s%d", op, &id);
if (strcmp(op, "in") == 0)
{
scanf("%d", &num);
insert(head, id, num, m);
}
else
out(head, id, m);
//printf("\ni=%d\n", i);
//print(head);
}
}
return 0;
}
/**************************************************************
Problem: 1334
User: liangrx06
Language: C
Result: Accepted
Time:60 ms
Memory:912 kb
****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: