# PTA一元多项式的乘法和加法c++

4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

DS课程组

16 KB

200 ms

AC代码：

#include <bits/stdc++.h>
using namespace std;
typedef struct ploynode *ploy;
struct ploynode
{
int coef;
int expon;
};
void attach(int c,int e,ploy *l){
ploy p;
p=(ploy)malloc(sizeof(struct ploynode));
p->coef=c;
p->expon=e;
*l=p;
}
ploy p,rear,t;
int c,e,N;
cin>>N;
if(!N) return NULL;
p=(ploy)malloc(sizeof(struct ploynode));
rear=p;
while(N--){
cin>>c>>e;
attach(c,e,&rear);
}
return p;
}
if(!p1) return p2;
if(!p2) return p1;
ploy t1,t2,p,rear,t;
t1=p1; t2=p2;
p=(ploy)malloc(sizeof(struct ploynode));
rear =p;
while(t1&&t2)
{
if(t1->expon==t2->expon){
int sum=t1->coef+t2->coef;
if(sum) attach(sum,t1->expon,&rear);
}
else if(t1->expon>t2->expon){
attach(t1->coef,t1->expon,&rear);
}
else{
attach(t2->coef,t2->expon,&rear);
}
}
while(t1){
attach(t1->coef,t1->expon,&rear);
}
while(t2){
attach(t2->coef,t2->expon,&rear);
}
return p;
}
ploy mult(ploy p1, ploy p2) {
if (!p1 || !p2) return NULL;
ploy t1, t2, p, rear, t;
t1 = p1;
p = (ploy)malloc(sizeof(struct ploynode));
rear = p;
while (t1) {
t2 = p2;
while (t2) {
attach(t1->coef*t2->coef, t1->expon + t2->expon, &rear);
}
}
t = p; p = p->link; free(t);
t1 = p;
t2 = p;
}
else if (t2->expon == t2->link->expon) {
t2->coef += t->coef;
free(t);
}
}
}
return p;
}
void printploy(ploy p){
if(!p){
cout<<"0 0";
return;
}
bool ans =true;
if(p->coef){
cout << p->coef<<' '<<p->expon;
ans = false;
}
while(p){
if(p->coef){
cout<<' '<<p->coef<<' '<<p->expon;
ans =false;
}
}
if(ans) cout<<"0 0";
}
int main(){
ploy p,q,qq,p1;
p1=mult(p,q);
printploy(p1);
cout<<endl;