PAT (Advanced Level) 1002 A+B for Polynomials (25 分)
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
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
學習
以上