#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
typedef struct node* ptrtonode;
struct node{
int a, i;
ptrtonode next;
};
typedef ptrtonode List;
int main() {
//读入多项式
int n;
int aa, ii;
cin >> n;
List l1 = new node;
l1->next = NULL;
ptrtonode head1 = l1;
for (int i = 0; i < n; i++) {
cin >> aa >> ii;
ptrtonode temp = new node;
temp->a = aa;
temp->i = ii;
temp->next = NULL;
head1->next = temp;
head1 = temp;
}
cin >> n;
List l2 = new node;
l2->next = NULL;
ptrtonode head2 = l2;
for (int i = 0; i < n; i++) {
cin >> aa >> ii;
ptrtonode temp = new node;
temp->a = aa;
temp->i = ii;
temp->next = NULL;
head2->next = temp;
head2 = temp;
}
//计算相加得到的多项式
List lsum = new node;
lsum->next = NULL;
ptrtonode temp1 = l1->next;
ptrtonode temp2 = l2->next;
ptrtonode temp3 = lsum;
while (temp1 && temp2) {
ptrtonode temp = new node;
if (temp1->i == temp2->i) {
if (temp1->a + temp2->a != 0) {
temp->a = temp1->a + temp2->a;
temp->i = temp1->i;
temp->next = NULL;
temp3->next = temp;
temp3 = temp;
}
temp1 = temp1->next;
temp2 = temp2->next;
}
else if (temp1->i > temp2->i) {
temp->a = temp1->a;
temp->i = temp1->i;
temp3->next = temp;
temp3 = temp;
temp1 = temp1->next;
}
else if (temp1->i < temp2->i) {
temp->a = temp2->a;
temp->i = temp2->i;
temp3->next = temp;
temp3 = temp;
temp2 = temp2->next;
}
}
while (temp1) {
temp3->next = temp1;
temp3 = temp3->next;
temp1 = temp1->next;
}
while (temp2) {
temp3->next = temp2;
temp3 = temp3->next;
temp2 = temp2->next;
}
//计算相乘得到的多项式
List lmuti = new node;
lmuti->next = NULL;
temp1 = l1->next;
temp2 = l2->next;
temp3 = lmuti;
while (temp1) {
while (temp2) {
ptrtonode newnode = new node;
newnode->next = NULL;
newnode->a = temp1->a * temp2->a;
newnode->i = temp1->i + temp2->i;
temp2 = temp2->next;
if (lmuti->next == NULL) {
temp3->next = newnode;
temp3 = temp3->next;
}
else {
ptrtonode temp4 = lmuti;
while (temp4->next != NULL && temp4->next->i > newnode->i) {
temp4 = temp4->next;
}
if(temp4->next == NULL) {
temp4->next = newnode;
}
else if (temp4->next->i == newnode->i) {
if (temp4->next->a + newnode->a != 0) {
temp4->next->a = temp4->next->a + newnode->a;
}
else {
if (temp4->next->next == NULL) {
temp4->next = NULL;
}
else {
temp4->next = temp4->next->next;
}
}
}
else if (temp4->next->i < newnode->i) {
newnode->next = temp4->next;
temp4->next = newnode;
}
}
}
temp1 = temp1->next;
temp2 = l2->next;
}
//输出相乘多项式
if (lmuti->next) {
while (lmuti->next->next) {
cout << lmuti->next->a << " " << lmuti->next->i << " ";
lmuti = lmuti->next;
}
cout << lmuti->next->a << " " << lmuti->next->i << endl;
}
else {
cout << "0" << " " << "0" << endl;
}
//输出相加多项式
if (lsum->next) {
while (lsum->next->next) {
cout << lsum->next->a << " " << lsum->next->i << " ";
lsum = lsum->next;
}
cout << lsum->next->a << " " << lsum->next->i;
}
else {
cout << "0" << " " << "0";
}
return 0;
}
09-10
1439
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交