【PAT】A1009. Product of Polynomials(STL map的使用)

【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);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值