设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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
#include<cstdio> #include<cstring> const int maxn = 2050; int main() { int n; int exp,coe; //exponent coefficient int add[maxn] = {0}; int arr[maxn] = {0}, mul[maxn] = {0}; memset(mul,0,sizeof(mul)); scanf("%d",&n); for (int i = 0; i < n; i++) { scanf("%d %d",&coe,&exp); add[exp] += coe; arr[exp] += coe; } scanf("%d",&n); for (int i = 0; i < n; i++) { scanf("%d %d",&coe,&exp); add[exp] += coe; for (int j = maxn; j >= 0; j--) { if (arr[j] != 0) { mul[j + exp] += arr[j] * coe; } } } int cnt_add = 0; int cnt_mul = 0; for (int i = 0; i < maxn; i++) { if (add[i] != 0) { cnt_add++; } if (mul[i] != 0) { cnt_mul++; } } if (0 == cnt_mul) { printf("0 0 "); } else { for (int i = maxn - 1; i >= 0; i--) //数组初始化是从0~maxn-1共maxn位 { if (mul[i] != 0) { printf("%d %d",mul[i],i); cnt_mul--; if (cnt_mul > 0) { printf(" "); } else { printf(" "); } } } } if ( 0 == cnt_add ) { printf("0 0 "); } else { for (int i = maxn; i >= 0; i--) { if (add[i] != 0) { printf("%d %d",add[i],i); cnt_add--; if (cnt_add > 0) { printf(" "); } else { printf(" "); } } } } return 0; }
函数调用:
#include<cstdio> #include<cstring> const int maxn = 2050; void print(int cnt,int *arr); int main() { int n; int exp,coe; //exponent coefficient int add[maxn] = {0}; int arr[maxn] = {0}, mul[maxn] = {0}; scanf("%d",&n); for (int i = 0; i < n; i++) { scanf("%d %d",&coe,&exp); add[exp] += coe; arr[exp] += coe; } scanf("%d",&n); for (int i = 0; i < n; i++) { scanf("%d %d",&coe,&exp); add[exp] += coe; for (int j = maxn; j >= 0; j--) { if (arr[j] != 0) { mul[j + exp] += arr[j] * coe; } } } int cnt_add = 0; int cnt_mul = 0; for (int i = 0; i < maxn; i++) { if (add[i] != 0) { cnt_add++; } if (mul[i] != 0) { cnt_mul++; } } print(cnt_mul,mul); print(cnt_add,add); return 0; } void print(int cnt,int *arr) { int temp_cnt = cnt; int *arr_temp = arr; if ( 0 == temp_cnt ) { printf("0 0 "); } else { for (int i = maxn - 1; i >= 0; i--) { if (arr_temp[i] != 0) { printf("%d %d",arr_temp[i],i); temp_cnt--; if (temp_cnt > 0) { printf(" "); } else { printf(" "); } } } } }