[PAT甲级]1002 A+B for Polynomials
以下所述均为个人理解,如有错误,还望指正
题目
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:
KKK N1N_1N1 aN1a_{N_1}aN1 N2N_2N2 aN2a_{N_2}aN2 ... NKN_KNK aNKa_{N_K}aNK
where KKK is the number of nonzero terms in the polynomial, NiN_iNi and aNia_{N_i}aNi (i=1,2,⋯ ,Ki=1, 2, \cdots , Ki=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤101 \le K \le 101≤K≤10,0≤NK<⋯<N2<N1≤10000 \le N_K < \cdots < N_2 < N_1 \le 10000≤NK<⋯<N2<N1≤1000.
Output Specification:
For each test case you should output the sum of AAA and BBB 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.
题解:数组
利用res数组来表示相加的得到的多项式
#include <bits/stdc++.h>
using namespace std;
double res[1010]={0};
int main()
{
int m, n;
int exp; // 指数
double coe; // 系数
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> exp >> coe;
res[exp] += coe;
}
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> exp >> coe;
res[exp] += coe;
}
int num = 0;
for (int i = 1009; i >= 0; i--)
{
if (res[i] != 0)
num++;
}
if (num == 0)
cout << 0;
else
{
cout << num;
for (int i = 1009; i >= 0; i--)
{
if (res[i] != 0)
{
cout << " "<<i<<" "<<fixed <<setprecision(1) << res[i];
}
}
}
cout << endl;
}
AC结果: