1009 Product of Polynomials (25 分)

本文介绍了一种解决多项式乘法问题的算法,通过使用数组或map存储多项式的系数和指数,实现了A和B两个多项式的乘法运算。文章详细解释了如何处理输入输出格式,以及如何利用map按key降序排序的技巧。

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N​K​​<⋯<N​2​​<N​1​​≤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

 思路:其实就是简单模拟,注意点,无论你是用数组 做还是用map在 遍历的时候,都要把maxn开到2000以上 因为两个1000的指数相乘得到的指数就有可能是2000

注意点:map内部是默认对key进行升序排序的,要使map按key降序排序 只需要实现map的第三个参数,map<int ,double,greater<int> > 这种方式。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#define ll long long 
using namespace std;
const int maxn=2100;
map<int,double,greater<int> > mp1,mp2,mp3;
int main()
{
	int n,m;
	int tmp1;double tmp2;
	cin>>n;
	for(int i=0;i<n;i++)
	{
	   cin>>tmp1>>tmp2;
       mp1[tmp1]=tmp2;
	}
	cin>>m;
	for(int i=0;i<m;i++)
	{
	   cin>>tmp1>>tmp2;
	   mp2[tmp1]=tmp2;
	}
	for(int i=0;i<=maxn;i++)
	{
	    if(mp1[i]!=0)
		{
		   for(int j=0;j<=maxn;j++)
		   {
		     if(mp2[j]!=0)
			 {
			    int ans=i+j;
				mp3[ans]+=mp1[i]*mp2[j];
			 }
		   }
		}
	}
	int num=0;
    for(int i=maxn;i>=0;i--)
	{
	   if(mp3[i])
	   {
		   num++;
	   }
	}
	printf("%d",num);
	for(int i=maxn;i>=0;i--)
	{
	   if(mp3[i])
	   {
		  printf(" %d %0.1f",i,mp3[i]);
	   }
	}
	printf("\n");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值