题目
原题大意:求两个多项式的数乘
关键单词对照翻译如下:
exponent 指数 coefficient 系数 polynomial 多项式 product 数乘
思路
- 最直接最快速的方法就是使用map,用2个map存储数据,然后用一个map输出结果。
- 这道题的坑,我踩到的主要是第一个错误。坑估计如下,这道题是存在最终系数全为0(不止一个项)的测试数据,所以必须使用删除系数0项的办法。
- 最后用了map的反向定位器,其使用介绍如下,注意要使用反向map容器。
注释的代码仅仅是为了探测更多测试点的信息,没什么用。
rbegin()
功能:返回一个指向反向 map 容器的第一个元素的定位器。
语法:const_reverse_iterator rbegin()const;
reverse_iterator rbegin();
说明:rbegin 与反向 map 容器一起使用,它的作用与 map 容器中的 begin 一样。当返回值为一个 const
_reverse _iterator,则 map 容器不会被修改。当返回值为一个 reverse _iterator,则 map 容器可被修改。函数返回值:返回一个指向反向 map 容器的第一个元素的反向双向定位器。
rend()
功能:返回一个指向反向 map 容器的最后元素后面的定位器。
语法:const_reverse_iterator rend() const;
reverse_iterator rend();
说明:rend 与反向 map 容器一起使用,它的作用与 map 容器中的 end 一样。当返回值为一个 const _reverse
_iterator,则 map 不会被修改。当返回值为一个 reverse _iterator,则 map 可被修改。函数返回值:返回一个指向反向 map 容器中的最后一个元素后面的反向双向定位器。
代码
#include <iostream>
#include <map>
#include <cstdio>
using namespace std;
int main(){
map<int,float>map1;
map<int,float>map2;
map<int,float>map3;
int n,m;
cin>>n;
for(int i=0;i<n;i++)
{
int temp;
float temp2;
cin>>temp>>temp2;
map1[temp]=temp2;
}
cin>>m;
for(int i=0;i<m;i++)
{
int temp;
float temp2;
cin>>temp>>temp2;
map2[temp]=temp2;
}
for(map<int,float>::iterator it=map1.begin();it!=map1.end();it++)
{
for(map<int,float>::iterator jt=map2.begin();jt!=map2.end();jt++)
{
map3[it->first+jt->first]+=it->second*jt->second;
}
}
// if(map3.size()==1){
// map<int,float>::iterator it=map3.begin();
// if(it->second==0)
// cout<<0;
// else
// cout<<1;
// }
// else
// cout<<map3.size();
for(map<int,float>::iterator i=map3.begin();i!=map3.end();)
{
if(i->second<=1e-15&&i->second>=-1e-15)
{
map3.erase(i);
break;
}
else
++i;
}
cout<<map3.size();
for(map<int,float>::reverse_iterator it=map3.rbegin();it!=map3.rend();it++)
{
if(it->second>=1e-5||it->second<=-1e-15)
printf(" %d %.1f",it->first,it->second);
}
return 0;
}
第一次写博客,交给pat。