题目描述
一个一元多项式可以看作由若干个一元单项式按降幂排列成的线性表。请编写程序对输入的两个一元多项式求和,并输出求和的结果。
输入格式
输入为两个一元多项式,每个一元多项式输入一行,按照降幂依次输入每个单项式的系数和指数,并以-1 -1作为结束。系数和指数均为整数,指数不小于0。
输出格式
输出为求和结果多项式,按照降幂依次输出每个单项的系数和指数,每个数值后面用一个空格隔开,输出结果多项式后换行。 系数为0的单项式不得输出——除非结果多项式就是0,则直接输出0。
输入样例 复制
2 7 3 5 12 1 6 0 -1 -1
7 5 9 4 3 0 -1 -1
输出样例 复制
2 7 10 5 9 4 12 1 9 0
数据范围与提示
数据范围:每个多项式的数据项数量不超过10000
分类标签
#include <iostream>
#include<cstring>
#include <cstdio>
using
namespace
std;
#define SIZE 10000
struct
node{
int
r;
int
e;
};
struct
NodeList{
node data[1000+5];
int
len;
};
void
zero(NodeList&a){
a.len=0;
}
void
input(NodeList&a){
int
r,e;
while
(cin>>r>>e){
if
(r==-1 &&e==-1)
break
;
else
{
a.data[a.len].r=r;
a.data[a.len].e=e;
a.len++;
}
}
}
void
add(NodeList a,NodeList b,NodeList &c){
int
i=0,j=0,k=0;
while
(i<a.len && j<b.len){
if
(a.data[i].e>b.data[j].e){
c.data[k].r=a.data[i].r;
c.data[k].e=a.data[i].e;
i++;
}
else
if
(a.data[i].e==b.data[j].e){
if
(a.data[i].r+b.data[j].r!=0){
c.data[k].r=a.data[i].r+b.data[j].r;
c.data[k].e=a.data[i].e;
i++,j++;
}
else
{
i++,j++;
continue
;
}
}
else
{
c.data[k].e=b.data[j].e;
c.data[k].r=b.data[j].r;
j++;
}
k++;
c.len++;
}
if
(i>=a.len){
while
(j<b.len){
c.data[k].r=b.data[j].r;
c.data[k].e=b.data[j].e;
k++,j++,c.len++;
}
}
else
{
while
(i<a.len){
c.data[k].r=a.data[i].r;
c.data[k].e=a.data[i].e;
i++,k++,c.len++;
}
}
}
void
output(NodeList a){
if
(a.data[0].r==0)cout<<0;
else
{
for
(
int
i=0;i<a.len;i++){
cout<<a.data[i].r<<
" "
<<a.data[i].e;
if
(i<a.len) cout<<
" "
;
}
}
}
int
main(){
NodeList a,b,c;
zero(a);
zero(b);
zero(c);
input(a);
input(b);
add(a,b,c);
output(c);
return
0;
}