#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
int coef;//常量
int exp;//系数
node* next;
}list;
//生成节点
node* newNode(int a,int b){
node* p=(node*)malloc(sizeof(struct node));
p->coef=a;
p->exp=b;
p->next=NULL;
return p;
}
//生成链表,将多项式转化成链表
list* newPoly(int n){
list* L=(node*)malloc(sizeof(struct node));
L->next=NULL;
int ac=0,ae=0;
list* Lastp=L;
list* temp=NULL;
for(int i=0;i<n;i++){
cin>>ac>>ae;
temp=newNode(ac,ae);
Lastp->next=temp;
Lastp=temp;
}
return L;
}/*
list* addPoly(list* A,list* B){//这一段错了,猜猜错哪
if(!A->next) return B;
if(!B->next) return A;
node* pa=A->next;
node* pb=B->next;
list* sum=(list*)malloc(sizeof(struct node));
sum->next=NULL;
list* Lastp=sum;
list* temp=NULL;
while(pa && pb){
if(pa->exp==pb->exp){if((pa->coef+pb->coef)!=0){
temp=newNode(pa->coef+pb->coef,pa->exp);
Lastp->next=temp;
Lastp=temp;
}
pa=pa->next;
pb=pb->next;
}else if(pa->exp>pb->exp){temp=newNode(pa->coef,pa->exp);
Lastp->next=temp;
Lastp=temp;
pa=pa->next;
}else{temp=newNode(pb->coef,pb->exp);
Lastp->next=temp;
Lastp=temp;
pb=pb->next;
}
}
while(pa){
temp=(list*)malloc(sizeof(struct node));
Lastp->next=temp;
Lastp=temp;
pa=pa->next;
}
while(pb){
temp=(list*)malloc(sizeof(struct node));
Lastp->next=temp;
Lastp=temp;
pb=pb->next;
}
return sum;
}*/
list* addPoly(list* A, list* B) {//链表相加
if(!A->next) return B;
if(!B->next) return A;//特殊情况
node* pa = A->next;
node* pb = B->next;
list* sum = (list*)malloc(sizeof(struct node));
sum->next = NULL;
list* Lastp = sum;
list* temp = NULL;//准备条件
while(pa && pb) {//分三种,1号链与2号链此位系数相同,常数相加,都向后挪一位
if(pa->exp == pb->exp) {
if((pa->coef + pb->coef) != 0) {
temp = newNode(pa->coef + pb->coef, pa->exp);
Lastp->next = temp;
Lastp = temp;
}
pa = pa->next;
pb = pb->next;
} else if(pa->exp > pb->exp) {//此节点1号大于2号,1号节点不变成为新节点一部分,1号挪
temp = newNode(pa->coef, pa->exp);
Lastp->next = temp;
Lastp = temp;
pa = pa->next;
} else { //此节点2号大于1号,2号节点不变成为新节点一部分,2号挪
temp = newNode(pb->coef, pb->exp);
Lastp->next = temp;
Lastp = temp;
pb = pb->next;
}
}
while(pa) {
temp = newNode(pa->coef, pa->exp);
Lastp->next = temp;
Lastp = temp;
pa = pa->next;
}
while(pb) { //两个while处理任意链较长多出部分
temp = newNode(pb->coef, pb->exp);
Lastp->next = temp;
Lastp = temp;
pb = pb->next;
}
return sum;
}
void printPoly(list* Poly){
list* current=Poly->next;
while(current){
cout<<current->coef<<"x^"<<current->exp;
if(current->next)
cout<<"+";
current=current->next;
}
cout<<endl;
}
int main(){//西北师范22级郝宏飞
int n,m;
cin>>n;
list* Poly1=newPoly(n);
cin>>m;
list* Poly2=newPoly(m);
list* result=addPoly(Poly1,Poly2);
printPoly(result);
return 0;
}