This time, you are supposed to find A+B where A and B are two polynomials.
Input
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
For each test case you should output the sum 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 to 1 decimal place.
Sample Input2 1 2.4 0 3.2 2 2 1.5 1 0.5
程序输入为两行:均为一个多项式,按 K N1 An1 N2 An2......Nk Ank,K代表的是多项式的非零项数,范围闭区间是[1,10],N1到Nk的范围区间是 1<= Nk <= ......<= N1 <= 1000;
Nk是指数,Ank是系数,遇到相同的指数,系数进行累加,从而合并成一个多项式。
例子输入:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
可以解析成:
第一行: 2个子项---1*2.4 + 0*3.2
第二行: 2个子项---2*1.5 + 1*0.5
其中指数部分,二者有重合,可以累加,结果有 1*(2.4 + 0.5)
输出:
3 2 1.5 1 2.9 0 3.2
可以理解成: 3个子项---2*1.5 + 1*2.9 + 0*3.2
思路:建立一个长度为最长范围的数组c,c[zs]=xs;(zs:指数 xs=系数),接受a,b数据的同时存入数组c中,统计数组中不为0的项数,然后反向输出所有不为0的指数和系数。
代码:
import java.util.Scanner;
public class b1002 {
public static void main(String[] args){
int m,n;
int xs;
float zs;
float[] c=new float[1001];
Scanner in=new Scanner(System.in);
m=in.nextInt();
for(int i=0;i<m;i++){
xs=in.nextInt();
zs=in.nextFloat();
c[xs]=zs;
}
n=in.nextInt();
for(int i=0;i<n;i++){
xs=in.nextInt();
zs=in.nextFloat();
c[xs]+=zs;
}
int s=0;
for(int i=0;i<c.length;i++){
if(c[i]!=0.0)s++;
}
System.out.printf("%d",s);
for(int i=1000;i>=0;i--){
if(c[i]!=0.0)
System.out.printf(" %d %.1f",i,c[i]);
}
}
}