您的位置:首页 > 其它

pat甲级1009-Product of Polynomials

2018-03-12 23:09 435 查看

1009. Product of Polynomials (25)

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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

算法设计:

pat甲级1002题要求实现了多项式加法,多项式乘法比多项式加法稍微复杂一点,需要一个多项式的每一项与另外一个多项式的每一项相乘,然后合并同类项。在此过程中,需要保存好被乘的那个多项式,为此,可以开辟一个double数组存储第一个多项式,其中数组下标表示指数,数组元素表示系数,另外再开辟一个double数组result储存多项式相乘结果。在读取第二个多项式的过程中直接用第二个多项式的每一项与存储好的第一个多项式的每一项相乘并将结果保存至result数组。然后按要求输出result数组即可。

注意点:

(1)如果两个多项式相加后没有系数非0的项,应该只输出"0",后面不能跟空格(2)两个多项式中某一项相乘并合并同类项后系数是0,就不能输出这一项,前面计算项数时,也不能把这一项算进去。(3)多项式最高指数不超过1000,但是相乘之后指数可以达到2000,所以result数组至少要开到2000

c++代码:

[cpp] view plain copy#include<bits/stdc++.h>  
using namespace std;  
double A[1005],result[2005];  
int main(){  
    int K;  
    scanf("%d",&K);  
    //读取第一个多项式存储到A数组中  
    while(K--){  
        int a;  
        double b;  
        scanf("%d%lf",&a,&b);  
        A[a]=b;  
    }  
    scanf("%d",&K);  
    //读取第二个多项式  
    while(K--){  
        int a;  
        double b;  
        scanf("%d%lf",&a,&b);  
        for(int i=0;i<1005;++i)  
            result[a+i]+=A[i]*b;//将相乘结果报错到result中  
    }  
    int size=0;  
    //统计系数不为0的项数  
    for(int i=0;i<2005;++i)  
        if(result[i]!=0.0)  
            ++size;  
    printf("%d",size);  
    //输出每一项  
    for(int i=2005;i>=0;--i)  
        if(result[i]!=0.0)  
            printf(" %d %.1f",i,result[i]);  
    return 0;  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 pat