线性结构2 一元多项式的乘法与加法运算(20 分)
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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
emmmmm,这一题A了有一点时间,有好多东西可以讨论。
先po代码:
#include <cstdio>
#include <cstdlib>
#include <map>
using namespace std;
typedef struct node* List;
typedef struct node{
int number;
int exp;
List next;
} Node;
void initList(List* L) {
*L = (List)malloc(sizeof(Node));
(*L)->next = NULL;
}
//划重点List *p,此处传地址
void insert(List *p, int x, int y) {
List temp = (List)malloc(sizeof(Node));
temp->number = x;
temp->exp = y;
(*p)->next = temp;
*p = temp; //更新尾巴
(*p)->next = NULL;
}
int Compare(int a, int b) {
if (a > b) return 1;
else if (a == b) return 0;
else return -1;
}
int main()
{
List L1, L2, sum;
initList(&L1);
initList(&L2);
initList(&sum);
//initList(&multi);
List p1 = L1;
List p2 = L2;
List sp = sum;
//List mp = multi;
int n1, n2;
scanf("%d", &n1);
int num1, num2;
for (int i = 0; i < n1; ++i) {
scanf("%d %d", &num1, &num2);
insert(&p1, num1, num2);
}
scanf("%d", &n2);
for (int i = 0; i < n2; ++i) {
scanf("%d %d", &num1, &num2);
insert(&p2, num1, num2);
}
p1 = L1->next;
p2 = L2->next;
while (p1 && p2) {
switch (Compare(p1->exp, p2->exp)) {
case 1:
insert(&sp, p1->number, p1->exp);
p1 = p1->next;
break;
case 0:
if (p1->number + p2->number != 0)
insert(&sp, p1->number + p2->number, p1->exp);
p1 = p1->next;
p2 = p2->next;
break;
case -1:
insert(&sp, p2->number, p2->exp);
p2 = p2->next;
break;
}
}
for (;p1;p1 = p1->next) insert(&sp, p1->number, p1->exp);
for (;p2;p2 = p2->next) insert(&sp, p2->number, p2->exp);
map<int, int, greater<int> > mult; /*第一个值是exp,第二个是number*/
for (List m = L1->next; m; m = m->next) {
for (List n = L2->next;n;n = n->next) {
//这里看有没有找到
auto iter = mult.find((m->exp)+(n->exp));
if (iter == mult.end()) {
//下标添加元素
mult[(m->exp)+(n->exp)] = (m->number)*(n->number);
}
else {
iter->second += (m->number)*(n->number);
}
}
}
//任意之一为0即为0,0
if(n1 && n2) {
auto temp = --mult.end();
for (auto i = mult.begin(); i != mult.end(); ++i) {
if(i->second || (i->second==0 && i->first==0)) {
printf("%d %d", i->second, i->first);
if (i != temp) printf(" ");
}
}
}
else {
printf("0 0");
}
printf("\n");
//只有当全为零多项式时才是else,这种情况即sum为空list
if(sum->next) {
for (List l = sum->next; l; l = l->next) {
printf("%d %d", l->number, l->exp);
if (l->next) printf(" ");
}
}
else {
printf("0 0");
}
return 0;
}
考虑点
- 结果有零多项式
- 输入有零多项式