原题
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,
and
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that
.
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
题目翻译
这次,你要求出 A+B,其中 A 和 B 是两个多项式。
输入规范:
每个输入文件包含一个测试用例。每个案例占 2 行,每行包含一个多项式的信息: 其中 K 是多项式中非零项的数目,
和
(i=1,2,⋯,K) 分别为指数和系数。给定
。
输出规范:
对于每个测试用例,应在一行中输出 A 和 B 的总和,格式与输入相同。请注意,每行末尾不得有多余的空格。请精确到小数点后 1 位。
解题思路
题目比较简单, N最大为1000,果断暴力求解。
代码(c++)
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n,x;
double a[N] = {0}; // 数组下标表示指数, 值为对应指数的系数
int main()
{
cin >> n; // 读入第一个多项式
int x;
double y;
for(int i = 0; i < n; i++){
cin >> x >> y;
a[x] += y;
}
cin >> n; // 读入第二个多项式
for(int i = 0; i < n; i++){
cin >> x >> y;
a[x] += y;
}
int count = 0; // 计算系数不为0的多项式数量
for(int i = 0; i <= 1000; i++) if(a[i] != 0) count++;
printf("%d", count);
for(int i = 1000; i >= 0; i--)
if(a[i] != 0) printf(" %d %.1lf", i, a[i]); // 先输出空格让末尾无多余空格
}