输入格式:
输入分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
百经波折,终于解决了这道题。
思路:
1.定义一个结构体,再定义四个结构体数组(a,b,c,d)
a: 用于输入第一个表达式
b:用于输入第二个表达式
c:用于存储两个表达式的乘积
d: 用于存储两个表达式的和
2.输入表达式
3.两个表达式相乘,结果放入c中
4.对表达式进行排序,这里用到了sort+cmp排序
5.写一个函数,功能:将保存结果的结构数组,如果发现相邻两项的指数一样,那么就将这两个项的系数相加到一个数组值,指数不变,另一个数组系数值设置为负数的最小项(题中说 绝对值 < = 1000,负的最小项可以设置为-1005) 起名字叫 add
6.两个表达式相加,结果放入d中
7.重复上述的 4 5 两个步骤
ps : 有些小细节上述步骤里没有提到,程序中会有体现
代码如下:
#include <iostream> #include <algorithm> using namespace std; const int maxn=100; const int minn=-1005; //负的最小项 struct node { int cor; //系数 int exp; //指数 node *next; }; bool flag=false; // 小细节1 :用于对结果的第一项的系数是否为0进行判断 int n,lena,lenb,lenc; node * List1,*List2,*List3; node CreatNode(node a[]) ///建立结构数组 { cin>>n; if(n==0) { a[0].cor=0; a[0].exp=0; } for(int i=0; i<n; i++) { cin>>a[i].cor; cin>>a[i].exp; } return *a; } void print(node c[]) ///打印结构数组 { if(c[0].cor==0){ //如果结果的第一项的系数是0 细节2 flag=true; } else cout<<c[0].cor<<" "<<c[0].exp; //注意输出格式 细节3 for(int i=1; i<=lenc-1; i++) { if(c[i].cor!=minn) { if(c[i].cor!=0) cout<<" "<<c[i].cor<<" "<<c[i].exp; } } if(flag==true) cout<<"0 0"; flag=false; //注意将标符改回来 细节4 } bool cmp(const node & a, const node &b) ///cmp比较 { return a.exp>b.exp; } node UnionNode(node a[],node b[],node d[]) ///将两个结构数组合并成一个大的结构数组 { int t=0; for(int i=0; i<lena; i++) { d[t].cor=a[i].cor; d[t].exp=a[i].exp; t++; } for(int i=0; i<lenb; i++) { d[t].cor=b[i].cor; d[t].exp=b[i].exp; t++; } return *d; } void add(node c[]) ///将数组a,b的值赋值给c并排好序后,在c中进行加法运算 { int t=lenc; for(int i=0; i<t-1; i++) { if(c[i].exp==c[i+1].exp) { c[i].cor=c[i].cor+c[i+1].cor; c[i+1].cor=minn; } } } node mulNode(node a[],node b[],node c[]) ///将两个结构数组相乘的值赋值给第三个结构数组 { int t=0; for(int i=0; i<lena; i++) { for(int j=0; j<lenb; j++) { c[t].cor=a[i].cor*b[j].cor; c[t].exp=a[i].exp+b[j].exp; t++; } } return *c; } void hh() { cout<<endl; } int main() { node a[maxn+1],b[maxn+1],c[maxn+1],d[maxn+1]; a[maxn]=CreatNode(a); ///建立第一个结构数组 lena=n; b[maxn]=CreatNode(b); ///建立第二个结构数组 lenb=n; lenc=lena*lenb; c[maxn]=mulNode(a,b,c); sort(c,c+lenc,cmp); add(c); print(c); hh(); //这里的hh()与下面一行被注销掉的换行语句作用一样 //cout<<endl; lenc=lena+lenb; d[maxn]=UnionNode(a,b,d); ///将两个结构数组合并起来为C sort(d,d+lenc,cmp); ///对C排序 add(d); ///C中的元素相加 print(d); return 0; }