时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:8393
解决:1551
-
题目描述:
-
一个复数(x+iy)集合,两种操作作用在该集合上:
1、Pop 表示读出集合中复数模值最大的那个复数,如集合为空 输出 empty ,不为空就输出最大的那个复数并且从集合中删除那个复数,再输出集合的大小SIZE;
2 Insert a+ib 指令(a,b表示实部和虚部),将a+ib加入到集合中 ,输出集合的大小SIZE;
最开始要读入一个int n,表示接下来的n行每一行都是一条命令。
-
输入:
-
输入有多组数据。
每组输入一个n(1<=n<=1000),然后再输入n条指令。
-
输出:
-
根据指令输出结果。
-
样例输入:
-
3 Pop Insert 1+i2 Pop
-
样例输出:
-
empty SIZE = 1 1+i2 SIZE = 0
-
提示:
-
模相等的输出b较小的复数。
a和b都是非负数。
思路:
定义一个复数结构体,同时定义比较操作,对结构体数组进行插入排序。
我写的代码有点复杂了,没必要非要用链表。
代码:
#include <stdio.h>
#include <stdlib.h>
#define N 1000
struct node {
int x;
int y;
struct node *next;
};
int size;
int squareSum(int x, int y)
{
return x*x+y*y;
}
struct node *insert(struct node *head, int x, int y)
{
if (head == NULL)
{
head = (struct node *)malloc(sizeof(struct node));
head->x = x;
head->y = y;
head->next = NULL;
printf("SIZE = %d\n", ++size);
return head;
}
struct node *p = head, *p0;
p0 = p;
while (p && squareSum(p->x, p->y) <= squareSum(x, y))
{
if (squareSum(p->x, p->y) == squareSum(x, y) && p->x > x)
break;
p0 = p;
p = p->next;
}
struct node *pnew = (struct node *)malloc(sizeof(struct node));
pnew->x = x;
pnew->y = y;
pnew->next = p;
printf("SIZE = %d\n", ++size);
if (p == head)
return pnew;
p0->next = pnew;
return head;
}
struct node * pop(struct node *head, int *x, int *y)
{
if (head == NULL)
{
printf("empty\n");
return head;
}
if (head->next == NULL)
{
printf("%d+i%d\n", head->x, head->y);
printf("SIZE = %d\n", --size);
return NULL;
}
struct node *p=head, *p0;
do {
p0 = p;
p = p->next;
} while (p->next != NULL);
printf("%d+i%d\n", p->x, p->y);
printf("SIZE = %d\n", --size);
p0->next = NULL;
return head;
}
int main(void)
{
int n, i, x, y;
struct node *head;
char command[N];
while (scanf("%d", &n) != EOF)
{
head = NULL;
size = 0;
for(i=0; i<n; i++)
{
scanf("%s", command);
if (command[0] == 'P')
{
head = pop(head, &x, &y);
}
else
{
scanf("%d+i%d", &x, &y);
head = insert(head, x, y);
}
}
}
return 0;
}
/**************************************************************
Problem: 1178
User: liangrx06
Language: C
Result: Accepted
Time:10 ms
Memory:912 kb
****************************************************************/