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]);
}
}
}