//库函数头文件包含
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
//函数状态码定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef struct {
int c;
int e;
}term,ElemType;
typedef struct LNode{
ElemType elem;
struct LNode* next;
}*LinkList,LNode;
typedef LinkList Poly;
Status PolyInit(Poly& P)
{
P = (LNode*)malloc(sizeof(LNode));
if (!P)exit(OVERFLOW);
P->next = NULL;
return OK;
}
void PolyCreate(Poly& P)
{
int n, a, b;
LNode* cur, * rear = P;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b;
cur = (LNode*)malloc(sizeof(LNode));
if (!cur)exit(OVERFLOW);
cur->elem.c = a;
cur->elem.e = b;
//cur->next = NULL;
rear->next = cur;
rear = rear->next;
}
rear->next = NULL;
}
void PolyPrint(Poly& P)
{
LNode* p = P->next;
if (!p)
{
cout << 0 << " " << 0 << endl;
return;
}
while (p)
{
if (p->next != NULL)
cout << p->elem.c << " " << p->elem.e << " ";
else
cout << p->elem.c << " " << p->elem.e;
p = p->next;
}
cout << endl;
}
void PolyCopy(Poly& P, Poly& PP)
{
LNode *p = PP->next, *q=P,*cur=NULL;
while (p)
{
cur = (LNode*)malloc(sizeof(LNode));
if (!cur)exit(OVERFLOW);
cur->elem.c = p->elem.c;
cur->elem.e = p->elem.e;
//cur->next = NULL;
q->next = cur;
q = q->next;
p = p->next;
}
q->next = NULL;
}
void PolySum(Poly& P1, Poly& P2)
{
LNode *ha = P1, *hb = P2, *pa = P1->next, *pb = P2->next;
while (pa && pb)
{
if (pa->elem.e > pb->elem.e)
{
pa = pa->next; ha = ha->next;
}
else if (pa->elem.e == pb->elem.e)
{
int sum = pa->elem.c + pb->elem.c;
if (sum == 0)
{
ha->next = pa->next; free(pa); pa = ha->next;//pa = ha; ha = ha->next;
hb->next = pb->next; free(pb); pb = hb->next;//pa = ha; ha = ha->next;
}
else
{
pa->elem.c = sum;
ha = pa; pa = pa->next; hb = pb, pb = pb->next;
}
}
else
{
hb->next = pb->next;
pb->next = ha->next;
ha->next = pb;
pb = hb->next;
ha = ha->next;
//pa = ha->next;
}
}
if (pb)
{
ha->next = pb;
}
}
void PolyMul(Poly& P1,Poly &P2)
{
Poly M[1000];
int a, b,i=0;
LNode *pb = P2->next,*pm=NULL;
while (pb)
{
a = pb->elem.c; b = pb->elem.e;
PolyInit(M[i]);
PolyCopy(M[i], P1);
pm = M[i]->next;
while (pm)
{
pm->elem.c = pm->elem.c * a;
pm->elem.e = pm->elem.e + b;
pm = pm->next;
}
i++; pb = pb->next;
}
for (int j = 1; j < i; j++)
{
PolySum(M[0], M[j]);
}
PolyPrint(M[0]);
}
int main()
{
Poly P1,P2,P3;
PolyInit(P1);
PolyCreate(P1);
PolyInit(P2);
PolyCreate(P2);
PolyInit(P3);
PolyCopy(P3, P1);
PolyMul(P1, P2);//多项式乘法
PolySum(P3, P2);//多项式加法
PolyPrint(P3);
return 0;
}