一元多项式的乘法与加法运算(数组解法)

02-线性结构2 一元多项式的乘法与加法运算

设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出 0 0。

输入样例:

1
2
4 3 4 -5 2  6 1  -2 0
3 5 20 -7 4 3 1

输出样例:

1
2
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>

void putX(int A[][2], int numA, int B[][2], int numB);
void putSum(int A[][2], int numA, int B[][2], int numB);
int main(){
int num1, num2;
scanf("%d", &amp;num1);
int Arr1[num1][2];
for(int i = 0; i < num1; i++){
scanf("%d", &amp;Arr1[i][0]);
scanf("%d", &amp;Arr1[i][1]);
}
scanf("%d", &amp;num2);
int Arr2[num2][2];
for(int i = 0; i < num2; i++){
scanf("%d", &amp;Arr2[i][0]);
scanf("%d", &amp;Arr2[i][1]);
}
putX(Arr1, num1, Arr2, num2);
putSum(Arr1, num1, Arr2, num2);
return 0;
}

void putX(int A[][2], int numA, int B[][2], int numB){
if(numA == 0 || numB == 0){
printf("0 0\n");
return;
}
int max = A[0][1] + B[0][1] + 1;
int Arr[max];
for(int i = 0; i < max; i++){
Arr[i] = 0;
}
for(int i = 0; i < numA; i++){
for(int k = 0; k < numB; k++){
Arr[A[i][1] + B[k][1]] += A[i][0] * B[k][0];
}
}
int isNeedSpace = 0;
for(int i = max -1; i > -1; i--){
if(Arr[i] == 0) continue;
if(isNeedSpace){
printf(" ");
}
printf("%d %d", Arr[i], i);
isNeedSpace = 1;
}
printf("\n");
return;
}

int compote(int a, int b){
if(a == b){
return 0;
}else if( a > b){
return 1;
}else{
return -1;
}
}

void putSum(int A[][2], int numA, int B[][2], int numB){
int i = 0, k = 0, isEmpty = 1, isNeedSpace = 0;
while(i < numA &amp;&amp; k < numB){
int ps = compote(A[i][1], B[k][1]);
int sum;
switch(ps){
case 0:
sum = A[i][0] + B[k][0];
if(sum == 0){
i++;
k++;
continue;
};
if(isNeedSpace) printf(" ");
printf("%d %d", sum, A[i][1]);
isNeedSpace = 1;
isEmpty = 0;
i++;
k++;
break;
case 1:
if(isNeedSpace) printf(" ");
printf("%d %d", A[i][0], A[i][1]);
isNeedSpace = 1;
isEmpty = 0;
i++;
break;
case -1:
if(isNeedSpace) printf(" ");
printf("%d %d", B[k][0], B[k][1]);
isNeedSpace = 1;
isEmpty = 0;
k++;
break;
}
}
if(i < numA){
for(;i < numA;i++){
if(isNeedSpace){
printf(" ");
}
printf("%d %d", A[i][0], A[i][1]);
isEmpty = 0;
isNeedSpace = 1;
}
}else if(k < numB){
for(;k < numB;k++){
if(isNeedSpace){
printf(" ");
}
printf("%d %d", B[k][0], B[k][1]);
isEmpty = 0;
isNeedSpace = 1;
}
}
if(isEmpty){
printf("0 0");
}
return;
}
Author

feng

Posted on

2019-03-11

Updated on

2024-03-14

Licensed under

Kommentare