PTA 02-线性结构2 一元多项式的乘法与加法运算
Posted fsh001
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA 02-线性结构2 一元多项式的乘法与加法运算相关的知识,希望对你有一定的参考价值。
PTA 02-线性结构2 一元多项式的乘法与加法运算
题目描述
设计函数分别求两个一元多项式的乘积与和。
输入格式
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入输出样例
输入样例#1
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例#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
题目思路
注意零多项式输出0 0,不用的动态空间要释放。
#include<iostream>
using namespace std;
typedef struct node {
int a[2];
node* next;
}node;
void attach(int e, int c, node** rear)
{
node* p = (node*)malloc(sizeof(node));
p->a[0] = e;
p->a[1] = c;
p->next = NULL;
(*rear)->next = p;
*rear = p;
}
node* add(node* p1, node* p2)
{
node* p = (node*)malloc(sizeof(node));
p->next = NULL;
node* rear = p;
p1 = p1->next;
p2 = p2->next;
while (p1 && p2) {
if (p1->a[1] > p2->a[1]) {
attach(p1->a[0], p1->a[1], &rear);
p1 = p1->next;
}
else if (p1->a[1] < p2->a[1]) {
attach(p2->a[0], p2->a[1], &rear);
p2 = p2->next;
}
else {
if (p1->a[0] + p2->a[0])
attach(p1->a[0] + p2->a[0], p1->a[1], &rear);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1) {
attach(p1->a[0], p1->a[1], &rear);
p1 = p1->next;
}
while (p2) {
attach(p2->a[0], p2->a[1], &rear);
p2 = p2->next;
}
return p;
}
node * mul(node* p1, int e, int c)
{
int e1, c1;
node* p = (node*)malloc(sizeof(node));
node* rear = p;
//p1 = p1->next;
while (p1->next) {
e1 = p1->next->a[0] * e;
c1 = p1->next->a[1] + c;
if (e1 == 0 && c1 == 0) {
node* t = p1->next;
p1->next = t->next;
free(t);
}
else {
rear->next = (node*)malloc(sizeof(node));
rear->next->a[0] = e1;
rear->next->a[1] = c1;
rear->next->next = NULL;
rear = rear->next;
p1 = p1->next;
}
}
return p;
}
int main()
{
int T, K, e, c;
node* nmul, * nadd,* tnmul,* fnmul;
node* rear1 = (node*)malloc(sizeof(node));
node* p1 = rear1;
node* rear2 = (node*)malloc(sizeof(node));
node* p2 = rear2;
cin >> T;
for (int i = 0; i < T; i++) {
cin >> e >> c;
attach(e, c, &rear1);
}
cin >> K;
for (int i = 0; i < K; i++) {
cin >> e >> c;
attach(e, c, &rear2);
}
nadd = add(p1, p2);
nmul = (node*)malloc(sizeof(node));
nmul->next = NULL;
for (node* tmp = p2->next; tmp; tmp = tmp->next)
{
tnmul = add(nmul,mul(p1, tmp->a[0], tmp->a[1]));
while (nmul) {
fnmul = nmul;
nmul = nmul->next;
free(fnmul);
}
nmul = tnmul;
}
nmul = nmul -> next;
if(!nmul)
cout <<"0 0"<<endl;
else{
while (nmul->next) {
cout << nmul->a[0] << " " << nmul->a[1] << " ";
nmul = nmul->next;
}
cout << nmul->a[0] << " " << nmul->a[1] << endl;
}
nadd = nadd->next;
if(!nadd)
cout << "0 0"<<endl;
else{
while (nadd->next) {
cout << nadd->a[0] << " " << nadd->a[1] << " ";
nadd = nadd->next;
}
cout << nadd->a[0] << " " << nadd->a[1] << endl;
}
return 0;
}
以上是关于PTA 02-线性结构2 一元多项式的乘法与加法运算的主要内容,如果未能解决你的问题,请参考以下文章