PAT 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 coeficients(系数), 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和B,求A*B的结果。

解题思路:两个多项式相乘,系数coeficients相乘,指数exponents相加,模拟一下即可。这里由于指数是连续的,系数不连续且是小数,所以可以用数组来保存多项式,指数作为数组下标,系数保存到数组中。最后按照指数递减的顺序输出所有的不为0的项即可。

decimal  

adj. 小数的;十进位的

n. 小数

Product

n. 乘积、产物

#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<map>
using namespace std;
int main()
{
   int n1,n2,cnt=0;
   int i,j,e;
   double c;
   double a[2010]={0.0},ans[2010]={0.0};
   scanf("%d",&n1);
   for(i=0;i<n1;i++)
   {
       scanf("%d %lf",&e,&c);
       a[e]=c;
   }
   scanf("%d",&n2);
   for(i=0;i<n2;i++)
   {
       scanf("%d %lf",&e,&c);
       for(j=0;j<1010;j++)
       {
           if(a[j]!=0)
           {
               if(a[j]*c>10.0)
               {
                   ans[j+e+1]+=(a[j]*c)/10.0;//产生进位
               }
               else
               {
                   ans[j+e]+=a[j]*c;//系数相乘,指数相加
               }
           }
       }
   }
   for(i=0;i<2010;i++)
   {
       if(ans[i]!=0)
       {
           cnt++;
       }
   }
   printf("%d",cnt);//所有不为0的项数数量
   for(i=2010-1;i>=0;i--)
   {
       if(ans[i]!=0)
       {
           printf(" %d %.1f",i,ans[i]);
       }
   }
    return 0;
}

 

posted @ 2019-08-20 16:53  王陸  阅读(180)  评论(0编辑  收藏  举报