设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
/* 数最大才不超过10000的 毫无MLE风险 差点就偷懒用数组存储写了 QvQ..*/ #include "iostream" #include "string" using namespace std; struct Node { int coef; int exp; Node* next; }; typedef Node* List; /* * 尾插法 */ List Attach(List rear, int coef,int exp) { List p = (List)malloc(sizeof(Node)); p->coef = coef; p->exp = exp; p->next = NULL; rear->next = p; rear = rear->next; return rear; } /* 多项式相加 */ List AddPoly(List l1,List l2) { List p = (List)malloc(sizeof(Node)); p->next = NULL; List rear = p; while (l1 != NULL && l2!= NULL) { if (l1->exp > l2->exp) { rear = Attach(rear, l1->coef,l1->exp); l1 = l1->next; } else if (l2->exp > l1->exp) { rear = Attach(rear,l2->coef,l2->exp); l2 = l2->next; } else { if (l1->coef + l2->coef != 0) rear = Attach(rear, l1->coef + l2->coef, l1->exp); l1 = l1->next; l2 = l2->next; } } while (l1 != NULL) { rear = Attach(rear, l1->coef, l1->exp); l1 = l1->next; } while (l2 != NULL) { rear = Attach(rear, l2->coef, l2->exp); l2 = l2->next; } return p->next; } List Multiply(List l1,List l2) { //多项式相乘 List p = (List)malloc(sizeof(Node)); p->next = NULL; List s = l2; List k = NULL; List rear = p; while (l1 != NULL) { l2 = s; rear = p; while (l2 != NULL) { rear = Attach(rear,l1->coef*l2->coef,l1->exp+l2->exp); l2 = l2->next; } k = AddPoly(k,p->next); l1 = l1->next; } return k; } List ReadPoly() { //读入多项式 List p = (List)malloc(sizeof(Node)); List rear = p; p->next = NULL; int n; cin >> n; for (int i = 0; i < n; i++) { int exp, coef; cin >> coef >> exp; rear = Attach(rear,coef,exp); } return p->next; } void Print(List l) { //打印多项式 int k = 0; if (l == NULL) { cout << "0 0"; } else { while (l != NULL) { if (k == 0) { cout << l->coef << " " << l->exp; k = 1; } else { cout << " " << l->coef << " " << l->exp; } l = l->next; } } cout << endl; } int main() { List l1, l2; List p; l1 = ReadPoly(); l2 = ReadPoly(); p = Multiply(l1, l2); Print(p); p = AddPoly(l1,l2); Print(p); return 0; }