This time, you are supposed to find A×B where A and B are two polynomials.
这一次,你应该找到A×B,其中A和B是两个多项式。
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
每个输入文件包含一个测试用例。每种情况占用2行,每行包含一个多项式的信息:
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.
其中K是多项式中非零项的数量,Ni和aNi(i=1,2,…,K)分别是指数和系数。给出了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.
对于每个测试用例,您应该在一行中输出A和B的乘积,格式与输入相同。请注意,每一行的末尾都不能有多余的空格。请精确到小数点后1位。
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存储指数和系数,然后用数学方法算出多项式相乘的结果,一个一个存储到一个新的map中
import java.util.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
Map<Integer,Double> map1 = new HashMap<>();
for(int i = 0 ; i < n1 ;i++)
{
int ex = sc.nextInt();//系数
double co = sc.nextDouble();//指数,一定要用doule存储
map1.put(ex,co);
}
int n2 = sc.nextInt();
Map<Integer,Double> map2 = new HashMap<>();
for(int i = 0 ; i < n2 ;i++)
{
int ex = sc.nextInt();
double co = sc.nextDouble();
map2.put(ex,co);
}
Map<Integer,Double> map3 = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});//用TreeMap存储,重写排序方法,从大到小
for(Integer x : map1.keySet())
{
for (Integer y : map2.keySet())
{
int ex = x + y;//指数相加
double co = map1.get(x) * map2.get(y);//系数相乘
if(!map3.containsKey(ex))//如果map3中还没有该指数的项
{
map3.put(ex,co);
}
else
{
double co2 = map3.get(ex);
map3.put(ex,co + co2);
}
}
}
int count = 0;//记录系数为0的项有多少个
for(Integer k : map3.keySet())
{
if(map3.get(k).equals(Double.valueOf(0)))
{
count++;
}
}
System.out.print(map3.size() - count);//这里一定要记得减去零项系数的个数,不然第一个测试点过不了
for(Integer k : map3.keySet())
{
if(map3.get(k) != 0)//如果不是非零项
{
System.out.printf(" %d %.1f",k,map3.get(k));
}
}
}
}