设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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>
#include<algorithm>
using namespace std;
typedef struct node
{
int cof;
int ind;
}node;
bool cmp(node x,node y)
{
return x.ind>y.ind;
}
int print(node res[],int size)
{
//bool flag=0;
if(res[0].ind==-1) {cout<<"0 0"<<endl;return 0;}
cout<<res[0].cof<<" "<<res[0].ind;
for(int i=1;i<size;i++)
{
if(res[i].ind!=-1){
cout<<" "<<res[i].cof<<" "<<res[i].ind;
//flag=1;
}
}
//if(flag==0) cout<<"0 0";
cout<<endl;
}
int main()
{
int x,y;
node b[1001],a[1001];
node res[20000],res1[20000];
cin>>x;
for(int i=0;i<x;i++)
{
cin>>a[i].cof>>a[i].ind;
}
cin>>y;
for(int i=0;i<y;i++){
cin>>b[i].cof>>b[i].ind;
}
if(x==0) {
cout<<"0 0"<<endl;
print(b,y);
return 0;
}
if(y==0){
cout<<"0 0"<<endl;
print(a,x);
return 0;
}
//求积
int m=0,p=0,q=0;
for(m=0;m<x;m++)
{
for(p=0;p<y;p++)
{
res1[q].cof=a[m].cof*b[p].cof;
res1[q].ind=a[m].ind+b[p].ind;
q++;
}
}
sort(res1,res1+q,cmp);
for(int z=0;z<(q-1);z++)
{
if(res1[z].ind==res1[z+1].ind)
{
res1[z].cof+=res1[z+1].cof;
if(res1[z].cof==0)
{
res1[z].cof=-1;
res1[z].ind=-1;
}
res1[z+1].cof=-1;
res1[z+1].ind=-1;
}
}
print(res1,q);
//求和
int k=0;
int i=0,j=0;
while(i<x&&j<y)
{
if(a[i].ind>b[j].ind){
res[k].cof=a[i].cof;
res[k].ind=a[i].ind;
k++;
i++;
}
else if(a[i].ind<b[j].ind){
res[k].cof=b[j].cof;
res[k].ind=b[j].ind;
k++;
j++;
}
else if(a[i].ind==b[j].ind){
res[k].cof=b[j].cof+a[i].cof;
if(res[k].cof==0){
res[k].cof=-1;
res[k].ind=-1;
}
else{
res[k].ind=a[i].ind;
}
k++;
i++;j++;
}
}
if(i<x){
while(i<x){
res[k].cof=a[i].cof;
res[k].ind=a[i].ind;
k++;i++;
}
}
if(j<y){
while(j<y)
{
res[k].cof=b[j].cof;
res[k].ind=a[i].ind;
k++;j++;
}
}
print(res,k);
}