【PAT】A1009. Product of Polynomials(STL map的使用)
@(PAT)
链接:https://www.patest.cn/contests/pat-a-practise/1009
思路:
1. 需要多项式相乘,遍历两个多项式,然后把结果储存,使用map。
2. map默认是按key从小到大排列的,如果需要从大到小排列或者按自己的需要排列,在创建map的时候需要修改第三个参数。
3. map的find的使用,如果找到就返回找到的iter,否则返回end。
4. PAT测试样例中,有一个点是系数为0的情况,需要在最后判断系数为0的情况,不要输出系数为0的项。
关于map:
http://www.cplusplus.com/reference/map/map/
关于map的排序:
http://blog.csdn.net/iicy266/article/details/11906189
My AC code:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
int k1, k2;
map<int, float> p1, p2;
map<int, float, greater<int> > res;
scanf("%d", &k1);
for (int i= 0; i< k1; i++) {
int e;
float c;
scanf("%d %f", &e, &c);
p1.insert(make_pair(e, c));
}
scanf("%d", &k2);
for (int i= 0; i< k2; i++) {
int e;
float c;
scanf("%d %f", &e, &c);
p2.insert(make_pair(e, c));
}
map<int, float>::iterator iter1;
map<int, float>::iterator iter2;
for (iter1= p1.begin(); iter1!= p1.end(); iter1++) {
for (iter2= p2.begin(); iter2!= p2.end(); iter2++) {
int ep;
float cof;
ep= iter1->first+ iter2->first;
cof= iter1->second* iter2->second;
map<int, float>::iterator ifind;
ifind= res.find(ep);
if (ifind== res.end()) {
res.insert(make_pair(ep, cof));
} else {
ifind->second+= cof;
}
}
}
int count= 0;
map<int, float>::iterator it;
for (it= res.begin(); it!= res.end(); it++) {
if (it->second!= 0) count++;
}
printf("%d ", count);
for (it= res.begin(); it!= res.end(); it++) {
if (it->second!= 0) {
if (it== res.begin()) {
printf("%d %.1f", it->first, it->second);
} else {
printf(" %d %.1f", it->first, it->second);
}
}
}
}