题目来源自PAT网站 https://www.patest.cn/
题目描述:
1009. Product of Polynomials (25)
This time, you aresupposed to find A*B where A and B are two polynomials.
InputSpecification:
Each input filecontains one test case. Each case occupies 2 lines, and each line contains theinformation of a polynomial: K N1 aN1 N2 aN2 ...NK aNK, where K is the number of nonzero terms in the polynomial, Niand aNi (i=1, 2, ..., K) are the exponents and coefficients,respectively. It is given that 1 <= K <= 10, 0 <= NK < ... < N2< N1 <=1000.
OutputSpecification:
For each test caseyou should output the product of A and B in one line, with the same format asthe input. Notice that there must be NO extra space at the end of each line.Please be accurate up to 1 decimal place.
SampleInput
2 1 2.4 0 3.2
2 2 1.5 1 0.5
SampleOutput
3 3 3.6 2 6.0 11.6
题目翻译:
1009.多项式的乘积
这一次,你需要计算出A*B,而A与B是两个多项式。
输入说明:
每个输入文件包含一个测试实例。每个实例有两行,每行是一个多项式的信息K N1 aN1 N2 aN2 ... NKaNK,K是多项式中非零项的个数,Ni 和 aNi (i=1, 2, ..., K) 分别是指数和系数,且1 <= K <= 10, 0 <= NK < ... < N2 < N1<=1000。
输出说明:
对于每个测试实例,你应该在一行上输出A与B的乘积,格式同输入时一样。注意在每行的末尾不能有多余的空格。精确度到一位小数。
输入样例:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
输出样例:
3 3 3.6 2 6.0 1 1.6
答案代码:
#include<cstdio>
struct poly
{
int k;
int exp[10];
double coe[10];
};
struct polyPro
{
int k;
int exp[100];
double coe[100];
};
void inputPoly(poly &p)
{
int i;
scanf("%d",&(p.k));
for(i=0;i<p.k;++i)
{
scanf("%d",&(p.exp[i]));
scanf("%lf",&(p.coe[i]));
}
}
void outputPro(polyPro &p)
{
int i;
printf("%d",p.k);
for(i=0;i<p.k;++i)
{
if(p.coe[i]>-0.05 && p.coe[i]<0.05)
continue;
printf(" %d %.1lf",p.exp[i],p.coe[i]);
}
}
void output(poly &p)
{//test function
int i;
printf("%d ",p.k);
for(i=0;i<p.k-1;++i)
printf("%d %.1lf ",p.exp[i],p.coe[i]);
printf("%d %.1lf\n",p.exp[i],p.coe[i]);
}
void exchange(polyPro &p,int i,int j)
{
int ti;
double td;
ti=p.exp[i];
p.exp[i]=p.exp[j];
p.exp[j]=ti;
td=p.coe[i];
p.coe[i]=p.coe[j];
p.coe[j]=td;
}
polyPro calPoly(poly &a,poly &b)
{
polyPro p;
int i1,i2,i3,i=0;
int expT;
double coeT;
for(i1=0;i1<a.k;++i1)
for(i2=0;i2<b.k;++i2)
{
expT=a.exp[i1]+b.exp[i2];
coeT=a.coe[i1]*b.coe[i2];
for(i3=0;i3<i;++i3)
{
if(expT==p.exp[i3])
{
p.coe[i3]+=coeT;
coeT=0;
}
}
if(coeT!=0)
{
p.exp[i]=expT;
p.coe[i]=coeT;
i++;
}
}
p.k=i;
for(i1=0,i2=0;i1<p.k;i1++)
{
if(p.coe[i1]>-0.05 && p.coe[i1]<0.05)
i--;
else
{
p.coe[i2]=p.coe[i1];
p.exp[i2]=p.exp[i1];
i2++;
}
}
p.k=i2;
int iMax;
for(i1=0;i1<p.k-1;++i1)
{
iMax=i1;
for(i2=i1+1;i2<p.k;++i2)
{
if(p.exp[iMax]<p.exp[i2])
iMax=i2;
}
if(iMax!=i1)
exchange(p,iMax,i1);
}
return p;
}
int main()
{
poly p1,p2;
inputPoly(p1);
inputPoly(p2);
//output(p1); output(p2);
polyPro p=calPoly(p1,p2);
//printf("@@@@@@@@@@@@\n");
outputPro(p);
return 0;
}
说明与心得:
我留下了代码的debug痕迹。
题目方法选择的不太好,尤其是输入有序这个条件我完全没有利用。反而用了选择排序。