具体要求
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2 <N1 ≤1000.
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
具体思路
恩。。很简单的多项式加法了,推荐去做做pta上面,浙大数据结构那一道多项式加法和乘法,比这个难些,而且这个可以用简单顺讯结构体来完成,十分基础。
具体代码
#include<stdio.h>
#include<stdlib.h>
#define MAX 1001
typedef struct node/*结构体*/
{
int zhi;
float xi;
}list;
list QW[MAX],AS[MAX],ZONG[MAX];/*三个全局结构体数组,对应,两个输入,一个输出*/
int CHA1()/*第一个结构体赋值*/
{
int i,k;
i=0;
scanf("%d",&k);
while(k--)
{
scanf("%d %f",&QW[i].zhi,&QW[i].xi);
i++;
}
return i;
}
int CHA2()/*第二个结构体赋值*/
{
int i,k;
i=0;
scanf("%d",&k);
while(k--)
{
scanf("%d %f",&AS[i].zhi,&AS[i].xi);
i++;
}
return i;
}
int JIA(int len1,int len2)/*相加*/
{
int i,j,v;/*记录数组的下标*/
float sum;
i=j=0;
v=0;
while((len1-i)&&(len2-j))/*两个都不为空*/
{
if( QW[i].zhi>AS[j].zhi)/*第一个的指数大于第二个*/
{
ZONG[v].zhi=QW[i].zhi;
ZONG[v].xi=QW[i].xi;
v++;
i++;
}
else if(QW[i].zhi<AS[j].zhi)
{
ZONG[v].zhi=AS[j].zhi;
ZONG[v].xi=AS[j].xi;
v++;
j++;
}
else
{
sum=QW[i].xi+AS[j].xi;
if((int)(sum)!=0)/*相等切系数加起来不等于0*/
{
ZONG[v].zhi=QW[i].zhi;
ZONG[v].xi=sum;
v++;
}
i++;
j++;
}
}
for(;len1-i>0;i++)/*接下来对剩余的加入这个数组*/
{
ZONG[v].zhi=QW[i].zhi;
ZONG[v].xi=QW[i].xi;
v++;
}
for(;len2-j>0;j++)
{
ZONG[v].zhi=AS[j].zhi;
ZONG[v].xi=AS[j].xi;
v++;
}
return v;
}
int main()
{
int len1,len2,len3;
len1=CHA1();
len2=CHA2();
len3=JIA(len1,len2);
printf("%d",len3);
for(int i=0;i<len3;i++)
printf(" %d %.1f",ZONG[i].zhi,ZONG[i].xi);/*注意输出格式*/
return 0;
}
思路这些真的推荐去看看,浙大的慕课,数据结构,超级棒的,代码很多不足,仅供参考,欢迎指正!