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:
K N
1
a
N
1
N
2
a
N
2
… N
K
a
N
K
where K is the number of nonzero terms in the polynomial, N
i
and a
N
i
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N
K
<⋯<N
2
<N
1
≤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
题意
每一行第一个数K代表这个多项式的项数,接下来有2K个数,每两个数代表多项式的阶数和前面的系数
给你这两个多项式计算这两个多项式的和输出和多项式有多少个非0项和以降序输出每一项的阶数和系数
思路
直接用double数组来表示多项式(看范围就1000,直接开大小为1000的数组就好了),数组下标为多项式的阶数里面的内容是系数,直接对应下标的数相加就好了,然后倒着遍历整个数组就好了,注意一下最后一个多项式最后不是空格是回车就好了
#include <bits/stdc++.h>
using namespace std;
double a[1005];
int main()
{
int k;
scanf("%d",&k);
for(int i=0;i<k;i++)
{
int n;
double x;
scanf("%d%lf",&n,&x);
a[n]+=x;
}
scanf("%d",&k);
for(int i=0;i<k;i++)
{
int n;
double x;
scanf("%d%lf",&n,&x);
a[n]+=x;
}
int cnt=0;
for(int i=0;i<1005;i++)
if(a[i]!=0)
cnt++;
printf("%d%c",cnt," \n"[cnt==0]);
for(int i=1000;i>=0;i--)
{
if(a[i]!=0)
printf("%d %.1lf%c",i,a[i]," \n"[--cnt==0]);
}
return 0;
}