1486 多项式相乘

来源:互联网 发布:指南针软件如何注销 编辑:程序博客网 时间:2024/06/03 14:45
描述

已知一元多项式A = anxn + … + a1x + a0, B = bnxn + … + b1x + b0

计算A * B

输入

输入数据有2m+1行。第一行为测试数据的组数m, 下面的2m行分别为m组测试数据。每组测试数据第一行是多项式A,第二行是多项式B。多项式中除常数项外的每一项的形式为AnXN,其中An是一个整数,表示该项的系数,X是变量名,N是该项的次数。各项与’+’或’-’之间有0个空格符。输入的多项式A和B的最高次数均不超过500,系数的绝对值不超过10000,次数大于等于0.

输出

输出结果有m行,分别对应m组测试数据。结果多项式按降幂方式排列,按常规的方式显示。例如,系数为0的项不输出;除常数项外,系数为1的项不显示系数。各项与运算符之间没有空格。

样例输入

23x5+19x62x-13x

样例输出

27x11+9x66x2-3x

 

 

#include <iostream>#include <string>using namespace std;int c[1002];int a[501];int b[501];void duru(int a[],string s){int coef, exp;coef=0;exp=0;int l=s.length();int j=0;int k=1;while(j<l){if(s[j]=='+'||s[j]=='-'){if(s[j]=='-')k=-1;j++;if(s[j]=='x'){coef=1;j++;if(s[j]<='9'&&s[j]>='0'){while(s[j]<='9'&&s[j]>='0'){exp=(exp*10+s[j]-'0');j++;}a[exp]=coef*k;coef=0;exp=0;k=1;}else{a[1]=coef*k;coef=0;exp=0;k=1;}}else{while(s[j]<='9'&&s[j]>='0'){coef=coef*10+s[j]-'0';j++;}if(s[j]=='x'){j++;if(s[j]<='9'&&s[j]>='0'){while(s[j]<='9'&&s[j]>='0'){exp=(exp*10+s[j]-'0');j++;}a[exp]=coef*k;exp=0;coef=0;k=1;}else{a[1]=coef*k;coef=0;exp=0;k=1;}}else{a[0]=coef*k;coef=0;exp=0;k=1;}}}else{if(s[j]=='x'){coef=1;j++;if(s[j]<='9'&&s[j]>='0'){while(s[j]<='9'&&s[j]>='0'){exp=(exp*10+s[j]-'0');j++;}a[exp]=coef*k;coef=0;exp=0;k=1;}else{a[1]=coef*k;coef=0;exp=0;k=1;}}else{while(s[j]<='9'&&s[j]>='0'){coef=coef*10+s[j]-'0';j++;}if(s[j]=='x'){j++;if(s[j]<='9'&&s[j]>='0'){while(s[j]<='9'&&s[j]>='0'){exp=(exp*10+s[j]-'0');j++;}a[exp]=coef*k;exp=0;coef=0;k=1;}else{a[1]=coef*k;coef=0;exp=0;k=1;}}else{while(s[j]<='9'&&s[j]>='0'){coef=coef*10+s[j]-'0';j++;}a[0]=coef*k;coef=0;exp=0;k=1;}}}}}int main(){int t;cin>>t;int j;for(int i=0; i<t; i++){string s1;string s2;cin>>s1;cin>>s2;for(j=0 ;j<501; j++){a[j]=0;b[j]=0;c[2*j]=0;c[2*j+1]=0;}duru(a, s1);duru(b, s2);int kk;for(j=0; j<501; j++){for(kk=0; kk<501; kk++)c[kk+j]+=a[j]*b[kk];}j=1001;if(c[j]==0&&j==0)cout<<c[j];while(c[j]==0&&j>=0){j--;}if(j==-1)cout<<"0";else{if(j>0){if(j!=1)if(c[j]!=1&&c[j]!=-1)cout<<c[j]<<"x"<<j;else{if(c[j]==1)cout<<"x"<<j;elsecout<<"-x"<<j;}elseif(c[j]!=1&&c[j]!=-1)cout<<c[j]<<"x";else{if(c[j]==1)cout<<"x";elsecout<<"-x";}j--;for(; j>0; j--){if(c[j]>0){if(j!=1){if(c[j]!=1)cout<<"+"<<c[j]<<"x"<<j;elsecout<<"+"<<"x"<<j;}else{if(c[j]!=1)cout<<"+"<<c[j]<<"x";else{cout<<"+"<<"x";}}}else{if(c[j]<0){if(j!=1)if(c[j]!=-1)cout<<c[j]<<"x"<<j;elsecout<<"-x"<<j;elseif(c[j]!=-1)cout<<c[j]<<"x";else{cout<<"-x";}}}}if(c[0]>0)cout<<"+"<<c[0];elseif(c[0]<0)cout<<c[0];}elseif(c[0]!=0)cout<<c[0];}cout<<endl;}return 0;}


 

原创粉丝点击