A1009 Product of Polynomials

1.在下采用链表做,锻炼debug能力。不得不说,链表真是很容易出现各种bug,好在最后都调通了。
2.核心代码是Attach函数和Mult函数,Attach尤为关键。
3.刚开始交上去第一个测试点万年过不去,后来想到可能链表里面有系数为0的项,遂在printf里面改之,依然不对,想了好久想到了cnt计数也要考虑,coef不为0才计数。
AC代码如下

#include <stdio.h>

struct node{
	int expon;
	double coef;
	node* next;
};

void Attach(node* p,node* t)
{
	if(p->next==NULL){
		t->next = NULL;
		p->next = t;
	}
	else{
		p = p->next;
		while(p){
			if(p->expon == t->expon){   //指数相同系数相加 
				p->coef += t->coef;
				break;
			}
			else{
				if(p->next){
					if(p->next->expon < t->expon){
						t->next = p->next;
						p->next = t;
						break;
					}
					else p = p->next;
				}
				else{			//p->next == NULL
					t->next = NULL;
					p->next = t;
					break;
				}
			}
		}
	}
}
node* Mult(node* p1,node* p2)
{
	p1 = p1->next;
	p2 = p2->next;
	
	node *pro = new node;
	pro->next = NULL;
	
	node *pp2;	//用另一个指针方便再循环
	pp2 = p2;
	while(p1){
		while(pp2){
			node* t = new node;
			t->expon = p1->expon + pp2->expon;
			t->coef = p1->coef * pp2->coef;
			if(t->coef)Attach(pro,t);
			pp2 = pp2->next;
		}
		p1 = p1->next;
		pp2 = p2;
	}
	return pro;
}
int main(int argc, char const *argv[])
{
	node *p1 = new node,*p2 = new node;
	p1->next = p2->next = NULL;

	int k1,k2;
	int expon;
	double coef;
	scanf("%d",&k1);
	for(int i=0;i<k1;i++){
		scanf("%d%lf",&expon,&coef);
		node* t = new node;
		t->expon = expon;
		t->coef = coef;
		Attach(p1,t);
	}
	scanf("%d",&k2);
	for(int i=0;i<k2;i++){
		scanf("%d%lf",&expon,&coef);
		node* t = new node;
		t->expon = expon;
		t->coef = coef;
		Attach(p2,t);
	}
	node *prdt = Mult(p1,p2);
	int cnt = 0;
	for(node* p=prdt->next;p!=NULL;p=p->next){
		if(p->coef)cnt++;
	}
	printf("%d",cnt);
	for(node* p=prdt->next;p!=NULL;p=p->next){
		if(p->coef)	printf(" %d %.1f",p->expon,p->coef);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值