PAT甲級真題——1009. Product of Polynomials
1009. Product of Polynomials
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
題目大意:
兩個多項式相乘
題目解析:
給出的程式碼是通過三個陣列分別儲存兩個多項式和結果,進行簡單模擬。看了別人的程式碼,發現也可以只用一個數組儲存多項式A,另一個多項式在輸入的時候直接計算即可。
具體程式碼:
#include<iostream> #include<cstdio> #include<cmath> using namespace std; #define MAXN 2010 #define EPSILON 0.01 //根據精度需要 double A[MAXN],B[MAXN],C[MAXN];//C存放相乘的結果 int main() { int k,a; double b;; scanf("%d",&k); while(k--) { scanf("%d%lf",&a,&b); A[a]=b; } scanf("%d",&k); while(k--) { scanf("%d%lf",&a,&b); B[a]=b; } for(int i=0; i<MAXN; i++) { if(fabs(A[i])>EPSILON)//如果係數不是0 for(int j=0; j<MAXN; j++) { if(fabs(B[j])>EPSILON) { //如果係數不是0 C[i+j]+=A[i]*B[j]; } } } int count=0; for(int i=0;i<MAXN;i++) if(fabs(C[i])>EPSILON) count++; printf("%d",count); for(int i=MAXN-1;i>=0;i--) if(fabs(C[i])>EPSILON) printf(" %d %.1f",i,C[i]); return 0; }