C语言根据模大小对复数排序,九度OJ 1178:复数集合 (插入排序)

这篇博客主要讨论了一种复数集合的操作实现,包括插入和删除最大模值复数的功能。代码中定义了一个复数结构体,并通过插入排序的方式维护集合。程序能够处理空集合情况,同时在模值相等时选择虚部较小的复数。对于输入的多组数据,程序能够正确执行Pop和Insert指令,并输出相应的集合大小。整个实现虽然较为复杂,但避免了使用链表,对于内存和时间效率有一定的考量。
摘要由CSDN通过智能技术生成

时间限制: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都是非负数。

来源:

2011年北京邮电大学网院研究生机试真题

思路:

定义一个复数结构体,同时定义比较操作,对结构体数组进行插入排序。

我写的代码有点复杂了,没必要非要用链表。

代码:

#include

#include

#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

{

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

****************************************************************/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值