您的位置:首页 > 运维架构

opj 多项式加法

2017-09-06 08:32 253 查看
将两个多项式按系数相加。

具体题目:多项式加法

我的做法是利用一个结点类与一个仅封装了两种操作的多项式类来实现。需要注意输出格式。具体代码如下:

#include<iostream>
#include<queue>
#include<stack>
#include<cmath>
#include<functional>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;

class Node{
public:
int coeff,power;
Node * next;
Node(int c,int p,Node* n=NULL){
coeff=c;
power=p;
next=n;
}
Node(Node *n){
next=n;
}
};

class Poly{
public:
Node * head,* tail;
Poly(){
head=tail=new Node(NULL);
}
void AddPair(int c,int po);
void Addnew(int c,int po);
~Poly(){
Node *p;
while(head!=NULL){
p=head;
head=head->next;
delete p;
}
}
};

void Poly::AddPair(int c, int po){
Node *p=new Node(c,po);
tail->next=p;
tail=p;
}
void Poly::Addnew(int c, int po){
Node *p=head;
while(p->next!=NULL && p->next->power>po){
p=p->next;
}
if(p->next!=NULL && p->next->power==po){
p->next->coeff+=c;
return;

}
Node *q=new Node(c,po,p->next);
p->next=q;
if(p==tail)
tail=q;
return;
}
int main(){
int n;
cin>>n;
while(n--){
int co,po;
Poly p1,p2,p3;
while(cin>>co>>po && po>=0){
if(co!=0) p1.Addnew(co, po);
}
while(cin>>co>>po && po>=0){
if(co!=0) p2.Addnew(co, po);
}
Node * a, *b;
a=p1.head->next,b=p2.head->next;

/* while(a!=NULL){
cout<<a->coeff<<" "<<a->power<<" /// ";

a=a->next;
}
cout<<endl<<endl;
while(b!=NULL){
cout<<b->coeff<<" "<<b->power<<" /// ";
b=b->next;
} */

while(a!=NULL || b!=NULL){
if(a==NULL){
if(b==NULL) break;
else{
p3.AddPair(b->coeff, b->power);
b=b->next;
continue;
}
}

if(b==NULL){
if(a==NULL) break;
else{
p3.AddPair(a->coeff, a->power);
a=a->next;
continue;
}
}

if(a->power>b->power){
p3.AddPair(a->coeff, a->power);
a=a->next;
continue;
}

if(a->power==b->power){
p3.AddPair(a->coeff+b->coeff, a->power);
a=a->next;
b=b->next;
continue;
}

if(a->power<b->power){
p3.AddPair(b->coeff, b->power);
b=b->next;
continue;
}

}//while for a & b

Node* p=p3.head->next;

p=p3.head->next;
while(p->next!=NULL){
if(p->coeff==0) {p=p->next;continue;}
printf("[ %d %d ] ",p->coeff,p->power);
p=p->next;
}
if(p->coeff!=0)printf("[ %d %d ]",p->coeff,p->power);
if(n!=0) printf("\n");
}//while for n
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opj