PAT (Advanced Level)1009解

因为最近在刷题库,想想就把本人可以想到的解法写到博客里,作为整理归纳。未必是最优解,还请各位高手多多包涵,能够指点指点。

题目要求
1009 Product of Polynomials (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:
在这里插入图片描述

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

解题思路
按照多项式笔算写法计算,题意如图
在这里插入图片描述
注意事项
采用数组暴力解法的时候,需要主要到多项式相乘,原来指数最大值为1000,相乘后最大值为2000,所以上限要跟着改变。
代码部分

#include<cstdio>
main(){
  float A[1001]={0.0},B[1001]={0.0},C[2002]={0.0};
  //A数组用来存放第一个,B数组用来存放第二个,C数组用来存放结果
  int ka,kb; 
  scanf("%d",&ka);
  int x;
  double y;
  for(int i=0;i<ka;i++){
  	scanf("%d",&x);
  	scanf("%lf",&y);
  	A[x]=y;
  }
  scanf("%d",&kb);
  for(int i=0;i<kb;i++){
  	scanf("%d",&x);
  	scanf("%lf",&y);
  	B[x]=y;
  }
  for(int i =0;i<=1000;i++){
  	for(int j=0;j<=1000;j++){
  		C[i+j]+=A[i]*B[j];
	  }
  }
  x=0;
  for(int i =0;i<=2001;i++){
  	if(C[i]!=0.0)
  	x++;
  }
  printf("%d",x);
  for(int i =2001;i>=0;i--){
  	if(C[i]!=0.0){
  		printf(" %d %.1lf",i,C[i]);			
	  }
  }
}
  

运行结果
在这里插入图片描述

发布了12 篇原创文章 · 获赞 3 · 访问量 1326

猜你喜欢

转载自blog.csdn.net/github_38201918/article/details/86688852