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
思路:其实就是简单模拟,注意点,无论你是用数组 做还是用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;
}
本文介绍了一种解决多项式乘法问题的算法,通过使用数组或map存储多项式的系数和指数,实现了A和B两个多项式的乘法运算。文章详细解释了如何处理输入输出格式,以及如何利用map按key降序排序的技巧。
1195

被折叠的 条评论
为什么被折叠?



