多项式加法和乘法
#include<bits/stdc++.h>
typedef struct node* ptr;
struct node{
int ex;
int coef;
ptr next;
};
ptr p1,p2;
ptr read(void)
{
ptr p;
int n;
scanf("%d",&n);
p=(ptr)malloc(sizeof(struct node));
p->next=NULL;
ptr ans=p;
for(int i=0;i<n;i++){
ptr tmp=(ptr)malloc(sizeof(struct node));
scanf("%d",&(tmp->coef));
scanf("%d",&(tmp->ex));
tmp->next=NULL;
p->next=tmp;
p=p->next;
}
return ans;
}
void print(ptr p){
int flag=0;
if(p->next==NULL)
{
printf("0 0\n");
return;
}
else{
p=p->next;
while(p)
{
if(!flag){
printf("%d %d",p->coef,p->ex);
flag=1;
p=p->next;
}
else{
printf(" %d %d",p->coef,p->ex);
p=p->next;
}
}
}
printf("\n");
}
ptr add(ptr p1,ptr p2)
{
ptr p,pp1=p1->next,pp2=p2->next;
p=(ptr)malloc(sizeof(struct node));
p->next=NULL;
ptr ans=p;
while(pp1&&pp2){
if(pp1->ex>pp2->ex){
p->next=pp1;
p=p->next;
pp1=pp1->next;
}
else if(pp1->ex<pp2->ex){
p->next=pp2;
p=p->next;
pp2=pp2->next;
}
else{
ptr tmp=(ptr)malloc(sizeof(struct node));
tmp->next=NULL;
tmp->coef=pp1->coef+pp2->coef;
tmp->ex=pp1->ex;
if(tmp->coef){
p->next=tmp;
p=p->next;
}
pp1=pp1->next;
pp2=pp2->next;
}
}
if(pp1)p->next=pp1;
if(pp2)p->next=pp2;
return ans;
}
ptr muti(ptr p1,ptr p2)
{
if(p1->next==NULL)return p1;
if(p2->next==NULL)return p2;
ptr t1=p1->next,t2=p2->next,t2head=t2;
ptr p=(ptr)malloc(sizeof(struct node));
ptr phead=p;
while(t2){
ptr tmp=(ptr)malloc(sizeof(struct node));
tmp->coef=t1->coef*t2->coef;
tmp->ex=t1->ex+t2->ex;
tmp->next=NULL;
p->next=tmp;
p=p->next;
t2=t2->next;
}
t1=t1->next;
while(t1)
{
t2=t2head;
while(t2)
{
p=phead;
ptr tmp=(ptr)malloc(sizeof(struct node));
tmp->coef=t1->coef*t2->coef;
tmp->ex=t1->ex+t2->ex;
tmp->next=NULL;
while(p->next&&tmp->ex<p->next->ex)
p=p->next;
if(p->next!=NULL&&tmp->ex==p->next->ex){
tmp->coef+=p->next->coef;
if(tmp->coef){
tmp->next=p->next->next;
p->next=tmp;
}
else{
p->next=p->next->next;
}
}
else{
tmp->next=p->next;
p->next=tmp;
}
t2=t2->next;
}
t1=t1->next;
}
return phead;
}
int main()
{
ptr p1,p2;
p1=read();
p2=read();
print(muti(p1,p2));
print(add(p1,p2));
return 0;
}