浙大数据结构课后习题 练习二 7-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
#include <iostream> #define M 10000 using namespace std; void print(int data[M]){ bool ini=true; for(int i=M-1;i>=0;i--){ if(data[i]){ if(!ini) cout<<" "; cout<<data[i]<<" "<<i; ini=false; } } if(ini) cout<<"0 0"; cout<<endl; } int main(){ int a[M]={0}; int b[M]={0}; int c[M]={0}; int d[M]={0}; int T,coef,expo; cin>>T; for(int i=0;i<T;i++){ cin>>coef>>expo; a[expo]=coef; } cin>>T; for(int i=0;i<T;i++){ cin>>coef>>expo; b[expo]=coef; } //乘法 for(int i=M-1;i>=0;i--){ if(a[i]){ for(int j=M-1;j>=0;j--){ if(b[j]){ c[i+j]+=(a[i]*b[j]); } } } } //加法 for(int i=M-1;i>=0;i--){ if(a[i]){ d[i]+=a[i]; } } for(int i=M-1;i>=0;i--){ if(b[i]){ d[i]+=b[i]; } } print(c); print(d); system("pause"); return 0; } /**在调试过程中,要切记是需要分清楚i和j*/