美文网首页
【PAT A1009】Product of Polynomial

【PAT A1009】Product of Polynomial

作者: AdmondGuo | 来源:发表于2018-06-29 18:10 被阅读0次

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 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (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

分析:

简单题:多项式的乘法,K是项的个数,a是系数,n是指数。按照正常计算方式计算就行,但是0号测试点没通过,还不知道是什么原因。
整体延用加法的hash结构,先用两个结构体存储两个多项式的数据,计算的时候再存到hash数组中。
hash[]的下标是n,数值是a(double)。输出的时候注意精度。

CODE:

#include <cstdio>
#include <iostream>
using namespace std;

#define maxn 2010
double temp[maxn];
struct poly{
    int n;
    double a;
}x[maxn],y[maxn];


int main(){
    int num=0;
    int m=0,n=0;
    int a;
    double b;
    cin>>m;
    for(int i=0;i<m;i++){
        cin>>a;
        cin>>b;
        x[i].n=a;
        x[i].a=b;
    }
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a;
        cin>>b;
        y[i].n=a;
        y[i].a=b;
    }
    for(int i=0;i<m;i++){   //相乘
        for(int j=0;j<n;j++){
            a=x[i].n+y[j].n;
            b=x[i].a*y[j].a;
            if(temp[a]!=0){
                temp[a]+=b;     
            }
            else{
                temp[a]=b;
                num++;
            }
        }
    }
    cout<<num;
    for(int i=maxn-1;i>0;i--){
        if(temp[i]!=0){
            cout<<" "<<i<<" ";
            printf("%.1f",temp[i]);
        }
    }   
    return 0;
}

相关文章

网友评论

      本文标题:【PAT A1009】Product of Polynomial

      本文链接:https://www.haomeiwen.com/subject/xfgoyftx.html