#include<iostream>
using namespace std;
typedef int ElementType;
typedef struct Node* PtrToNode;
typedef PtrToNode LinkList;
typedef PtrToNode Position;
struct Node {
ElementType Coefficient;
ElementType Exponent;
Position Next;
};
LinkList CreatList(int n) {
LinkList head;
Position rear, p;
ElementType coe, exp;
head = (LinkList)malloc(sizeof(struct Node));
rear = head;
while (n--) {
cin >> coe >> exp;
p = (LinkList)malloc(sizeof(struct Node));
p->Coefficient = coe;
p->Exponent = exp;
rear->Next = p;
rear = p;
}
rear->Next = NULL;
return head;
}
LinkList Add_List(LinkList a, LinkList b) {
LinkList ha, hb, hc;
Position rear, ptr;
ElementType temp;
ha = a->Next;
hb = b->Next;
hc = (LinkList)malloc(sizeof(struct Node));
rear = hc;
while (ha && hb) {
ptr = (LinkList)malloc(sizeof(struct Node));
if (ha->Exponent > hb->Exponent) {
ptr->Exponent = ha->Exponent;
ptr->Coefficient = ha->Coefficient;
ha = ha->Next;
rear->Next = ptr;
rear = ptr;
}
else if (ha->Exponent < hb->Exponent) {
ptr->Exponent = hb->Exponent;
ptr->Coefficient = hb->Coefficient;
hb = hb->Next;
rear->Next = ptr;
rear = ptr;
}
else {
temp = ha->Coefficient + hb->Coefficient;
if (temp) {
ptr->Exponent = ha->Exponent;
ptr->Coefficient = temp;
rear->Next = ptr;
rear = ptr;
}
ha = ha->Next;
hb = hb->Next;
}
}
if (ha == NULL) {
while (hb) {
ptr = (LinkList)malloc(sizeof(struct Node));
ptr->Exponent = hb->Exponent;
ptr->Coefficient = hb->Coefficient;
hb = hb->Next;
rear->Next = ptr;
rear = ptr;
}
}
if (hb == NULL) {
while (ha) {
ptr = (LinkList)malloc(sizeof(struct Node));
ptr->Exponent = ha->Exponent;
ptr->Coefficient = ha->Coefficient;
ha = ha->Next;
rear->Next = ptr;
rear = ptr;
}
}
rear->Next = NULL;
return hc;
}
LinkList Mul_List(LinkList a, LinkList b) {
LinkList ha, hb, hc;
Position rear, ptr, c;
ha = a->Next;
hb = b->Next;
hc = CreatList(0);
if (ha == NULL || hb == NULL) return hc;
while (ha) {
c = (LinkList)malloc(sizeof(struct Node));
rear = c;
hb = b->Next;
while (hb) {
ptr = (LinkList)malloc(sizeof(struct Node));
ptr->Exponent = ha->Exponent + hb->Exponent;
ptr->Coefficient = ha->Coefficient * hb->Coefficient;
hb = hb->Next;
rear->Next = ptr;
rear = ptr;
}
rear->Next = NULL;
hc = Add_List(hc, c);
ha = ha->Next;
}
return hc;
}
void Print(LinkList L) {
LinkList hc;
int f = 0;
hc = L->Next;
if (hc == NULL) cout << "0 0";
while (hc) {
if (f) cout << " ";
else f = 1;
cout << hc->Coefficient << " " << hc->Exponent;
hc = hc->Next;
}
cout << endl;
}
int main() {
int n1, n2;
LinkList L1, L2, L3, L4;
cin >> n1;
L1 = CreatList(n1);
cin >> n2;
L2 = CreatList(n2);
L3 = Mul_List(L1, L2);
L4 = Add_List(L1, L2);
Print(L3);
Print(L4);
return 0;
}
09-22