[PAT甲级]1009 Product of Polynomials (25 分)

题目

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 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.

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进行遍历即可,也可以使用数组的方法,注意系数为0的情况要被删除!
从这道题里面可以巩固一下map的遍历及自定义排序输出!

代码

#include<iostream>
#include<stdio.h>
#include<map>
using namespace std;

int main(){
    map<int,float> m1;
    map<int,float,greater<int>> m3;
    
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        int x;float y;
        cin>>x>>y;
        m1[x]=y;
    }
    
    cin>>n;
    for(int i=0;i<n;i++){
        map<int,float>::iterator it1=m1.begin();
        int x;float y;
        cin>>x>>y;
        for(;it1!=m1.end();it1++){
            int u = it1->first+x;
            float v = it1->second*y;
            if(m3.find(u)==m3.end()){
                m3[u]=v;
            }else{
                m3[u]+=v;
                if(m3[u]==0.0){
                    m3.erase(u);
                }
            }
        }
    }
    cout<<m3.size();
    map<int,float,greater<int>>::iterator it3=m3.begin();
    for(;it3!=m3.end();it3++){
            printf(" %d %.1f",it3->first,it3->second);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 天下熙熙皆为利来,天下攘攘皆为利往。 街道上的行人匆匆,每个人的脸上摆着一张淡漠。步伐宛如上了弦...
    灵语灬阅读 202评论 0 1
  • 一屋两人 三餐四季 五次 狗在跑, 我在闹, 他在笑。 夏天的傍晚一起去散步, 回家的路上 顺手买一个西瓜, 你说...
    静女说怿阅读 149评论 0 0
  • 你自己打动自己 港乐或后摇 歇斯底里和平寂 用廉价的像素拍出色彩冷淡的静物图 清晨四点在汽车没有肆无忌惮地轰鸣的街...
    廿无肆阅读 181评论 0 0