1002 A+B for Polynomials (25 分)
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 N1 aN1 N2 aN2 … NK aNK
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
Code
#include <iostream>
#include <string>
#include <map>
#include <iomanip>
using namespace std;
int main()
{
const int numOfPoly = 2; // 相加的多项式个数
int numOfTerms[numOfPoly];
map<int, float> polynomials[numOfPoly]; // 用来保存加数多项式的map, <exponent, coefficient>
//-------------------输入加数多项式-----------------//
for (int i = 0; i < numOfPoly; i++)
{
cin >> numOfTerms[i];
for (int j = 0; j < numOfTerms[i]; j++)
{
int exp;
float coeff;
cin >> exp >> coeff;
polynomials[i][exp] = coeff;
}
}
//--------------------输入完成----------------------//
map<int, float> sumPolynomial; // 用来保存和多项式的map
for (int i = 0; i < numOfPoly; i++) // 遍历每个加数多项式
{
for (auto it : polynomials[i]) // 遍历每个加数多项式的每一项
{
auto itOfSum = sumPolynomial.find(it.first); // 查找和多项式中是否有exponent相同的项
if (itOfSum != sumPolynomial.end()) // 如果有,coefficient相加
{
itOfSum->second += it.second;
if (itOfSum->second == 0) // 注意,如果相加等于0, 删去这一项
sumPolynomial.erase(itOfSum);
}
else // 如果没有, 在和多项式中加入这一项
{
sumPolynomial[it.first] = it.second;
}
}
}
cout << sumPolynomial.size(); // 输出项数
map<int, float>::reverse_iterator rIter;
for (rIter = sumPolynomial.rbegin(); rIter != sumPolynomial.rend(); rIter++) //反向遍历输出,注意精确到小数点后一位
{
cout << " " << rIter->first << " " << setiosflags(ios::fixed) << setprecision(1) <<rIter->second;
}
cout << endl;
return 0;
}
思路
本题目要求模拟多项式相加,如果用map容器,以指数(exponent)为键(key),以它的系数(coefficient)为值(value),那么,A、B两式相加时,A可以直接通过每一项的指数,找到B是否有指数相同的项,如果有就把值相加。具体实现方式请见代码注释。
warning
- Please be accurate to 1 decimal place. 注意精确到小数点后一位,如果没有注意这个,测试点1会错。
- 如果系数相加等于0那么要把这一组<exponent, coeffcient>删掉, 如果没有注意这个, 测试点3~6都会错。
关于C++ STL map的使用方法可以去
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
学习
关于C++11 auto遍历可以去
https://blog.csdn.net/qq_40213457/article/details/80720170
学习
以上