PAT Advanced 1009. Product of Polynomials
1. Problem Description:
This time, you are supposed to find \(A×B\) where \(A\) and \(B\) are two polynomials.
2. 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}\)
where \(K\) is the number of nonzero terms in the polynomial, \(N_i\) and \(a_{N_i}\) (\(i=1,2,⋯,K\)) are the exponents and coefficients, respectively. It is given that \(1≤K≤10\), \(0≤N_K<⋯<N_2<N_1≤1000\).
3. Output Specification:
For each test case you should output the product 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 up to 1 decimal place.
4. Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
5. Sample Output:
3 3 3.6 2 6.0 1 1.6
6. Performance Limit:
Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB
思路:
利用map<int, double>
类型存储多项式 \(A\) 和 \(B\),以及二者相乘的结果res
。模拟多项式乘法,遍历 \(A\) 的每一项与 \(B\) 的每一项相乘并存储结果到res
,最后遍历res
统计非零项的个数并进行输出。
My Code & Result:
#include <iostream>
#include <map>
using namespace std;
int main(void)
{
map<int, double> num1, num2;
map<int, double> res;
int termCount=0;
int i=0; // iterator
int tempExp = 0;
double tempCoef = 0.0;
cin >> termCount;
for(i=0; i<termCount; ++i) // input num1
{
cin >> tempExp >> tempCoef;
num1[tempExp] = tempCoef;
}
cin >> termCount;
for(i=0; i<termCount; ++i) // input num2
{
cin >> tempExp >> tempCoef;
num2[tempExp] = tempCoef;
}
for(const auto &i : num1) // range for num1
{
for(const auto &j : num2) // range for num2
{
tempExp = i.first + j.first;
tempCoef = i.second * j.second;
res[tempExp] += tempCoef;
}
}
termCount=0;
for(const auto & w: res) // count the nonzero term
{
if(w.second != 0.0) ++termCount;
}
cout << termCount;
for(auto it= res.rbegin(); it != res.rend(); ++it)
{
if(it->second != 0.0)
{
printf(" %d %.1f", it->first, it->second);
}
}
printf("\n");
// for(const auto &w:num1) // range for num1
// {
// cout << w.first << " " << w.second << " ";
// }
// cout << endl;
// for(const auto &w:num2) // range for num2
// {
// cout << w.first << " " << w.second << " ";
// }
return 0;
}
Compiler
C++ (g++)
Memory
468 / 65536 KB
Time
4 / 400 ms
标签:tempCoef,Product,tempExp,num1,res,second,1009,PAT,termCount
From: https://www.cnblogs.com/tacticKing/p/17389355.html