题目来源:PAT(甲级)1009 Product of 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 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.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 3 3.6 2 6.0 1 1.6
题目大意: 多项式乘法的计算
题目思路:
- 利用map存储两个需要计算的多项式
- 通过遍历进行多项式各项的乘法运算,并存储到新的map中(为什么选择map? 因为map可以进行自动排序!!!)
- 按照要求输出
注意事项:
- 第一个测试点样例中考虑到了系数为0的情况,这种情况下要将该项删除,并且各项要按照指数降序的顺序的排列,由于我用的是map就不用再进行排序的操作
- 计算共有几项的时候要记得出去系数为0的项
- 最后输出的时候,系数如果为整数记得保留一位小数,我用的是C语言的输出办法 printf ( “%.lf” , num )
#include<iostream>
#include<map>
using namespace std;
struct non {
int ex;
float co;
};
int main()
{
int K1, K2;
cin >> K1;
int ex;
float co;
map<int, float>re;
map<int, float>m1;
map<int, float>m2;
for (int i = 0;i < K1;i++)
{
cin >> ex >> co;
m1.insert(pair<int, float>(ex, co));
}
cin >> K2;
for (int i = 0;i < K2;i++)
{
cin >> ex >> co;
m2.insert(pair<int, float>(ex, co));
}
//做多项式乘法
int num = 0;
int temp_ex;
float temp_co;
map<int, float>::iterator it1, it2;
for (it1 = m1.begin();it1 != m1.end();it1++) {
for (it2 = m2.begin();it2 != m2.end();it2++) {
temp_ex = it1->first + it2->first;
temp_co = it1->second*it2->second;
//方法一:利用迭代器进行遍历
/*map<int, float>::iterator iter = re.find(temp_ex);
if (iter == re.end())
{
re.insert(pair<int, float>(temp_ex, temp_co));
}
else
{
iter->second += temp_co;
if (iter->second == 0.0)
re.erase(iter->first);
}*/
//方法二:不使用迭代器
if (re.find(temp_ex) == re.end())
{
re[temp_ex] = temp_co;
}
else
{
re[temp_ex] += temp_co;
if (re[temp_ex] == 0.0)
re.erase(temp_ex);
}
}
}
map<int, float>::reverse_iterator it;
cout << re.size(); //统计大小
for (it = re.rbegin();it != re.rend();it++)
{
cout << " " << it->first << " ";
printf("%.1lf", it->second);
}
cout << endl;
return 0;
}
map的用法参考:https://blog.csdn.net/forever__1234/article/details/89647975