PAT Product of Polynomials[一般]

1009 Product of Polynomials (25)(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 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (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

#include <iostream>
#include <cstring>
#include <cstdio>
#include<map>
#include<stack>
#include<math.h>
using namespace std;
#define EPSION 0.1
map<int,double> mp;
map<int,double,greater<int> > mp2;
int main()
{
    //freopen("1.txt","r",stdin);
    int k,mi;
    double xi;
    scanf("%d",&k);
    for(int i=0;i<k;i++){
        scanf("%d%lf",&mi,&xi);
        mp[mi]=xi;
    }
    scanf("%d",&k);
    int t;
    double sz;
    for(int i=0;i<k;i++){
        scanf("%d%lf",&mi,&xi);
        //遍历,这样复杂度好高啊,但是感觉也只能这样了
        for(map<int,double>::iterator it=mp.begin();it!=mp.end();it++){
            t=it->first;
            sz=it->second;
            t+=mi;
            sz*=xi;

            if(mp2.count(t)==0)
                mp2[t]=sz;
            else
                mp2[t]+=sz;
        }
    }
//接下来就是对map的关键字进行排序了。//自动的?
    //printf("%d",mp2.size());//应该不能直接输出size
    int ct=0;
    for(map<int,double>::iterator it=mp2.begin();it!=mp2.end();it++){
        if(fabs(it->second)>=1e-6)
            ct++;
    }
    printf("%d",ct);
    for(map<int,double>::iterator it=mp2.begin();it!=mp2.end();it++){
        if(fabs(it->second)>=1e-6)
            printf(" %d %.1f",it->first,it->second);
    }
    return 0;
}

//第一次提交出现了多种错误,格式错误和答案错误。。后来好几次提交都是20分。。本来以为会很简答,都不想上手写了。但是却搞了1.5h,真是醉了。

本题就是模拟多项式相乘。

1.多项式相乘可能系数会很小,这样计算机就不能识别,那么系数就为0.(也是因为这个一直提交只得了20分,不能直接输出mp2.size(),血的教训)

也就是说以后出现double相乘就要考虑是否会越最低界,

2.使用map时,它的关键字如果是可比较的,那么就会自动根据从小到大的顺序进行排序,如果需要反序,因为map默认的时less比较,那么就加上greater<int>就可以了,实现了map排序。

3.虽然说用数组可能会更简单,但是我觉得如果对map的操作比较熟悉了,也是一样的简单。

 
原文地址:https://www.cnblogs.com/BlueBlueSea/p/9340404.html