一、题目描述
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
K N_1 a_{N_1} N_2 a_{N_2} ... N_k a_{N_k}
KN1aN1N2aN2...NkaNk
where K is the number of nonzero terms in the polynomial,
N
i
N_i
Ni and
a
N
i
(
i
=
1
,
2
,
.
.
.
,
K
)
a_{N_i}(i = 1, 2, ..., K)
aNi(i=1,2,...,K) are the exponents and coefficients, respectively. It is given that
1
≤
K
≤
10
1 \leq K \leq 10
1≤K≤10,
0
≤
N
K
<
.
.
.
<
N
2
<
N
1
≤
1000
0 \leq N_K < ... < N_2 <N_1 \leq 1000
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
二、解题思路
根据题意,多项式的次数必然是整数,而系数则可以是小数,所以在定义变量时,我们可以定义一个整型,一个浮点型。设置一个数组,存放各项系数,用数组下标代表对应指数,进行两次输入,将对应下标的系数直接相加,随后倒序遍历数组,用一个vector来存放非0的指数(ans),ans[i]则表示系数不为零的指数,a[ans[i]]即为对应系数。
三、AC代码
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
double a[1001] = {0};
int main()
{
int K, temp, cnt = 0;
double tmp;
vector<int> ans;
for(int i=0; i<2; i++)
{
scanf("%d", &K);
for(int j=0; j<K; j++)
{
scanf("%d%lf", &temp, &tmp);
a[temp] += tmp;
}
}
for(int k=1000; k>=0; k--)
{
if(a[k] != 0)
{
cnt++;
ans.push_back(k);
}
}
int sze = ans.size();
printf("%d", cnt);
if(cnt != 0)
{
for(int m=0; m<sze; m++)
printf(" %d %.1f", ans[m], a[ans[m]]);
}
return 0;
}