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 Input
2 1 2.4 0 3.2 2 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3.2
思路:因为题目给了指数的范围<1000,利用数组实现简易的Hash表。
PS:题目有一个不严谨的地方,判断系数和是否为0这里。只用简单的 coffi[i]!=0 是不对的,如果系数的绝对值<0.05,在保留一位小数的情况下就成了0,0是不应该被输出的。正确的判断形式应该是Math.abs(coffi[i])>=0.05,两种写法都可以通过测试用例。
1 import java.util.*; 2 public class Main { 3 public static void main(String[] args) { 4 Scanner in = new Scanner(System.in); 5 int K=in.nextInt(); 6 float[] coffi=new float[1001]; 7 for(int i=0;i<K;i++){ 8 coffi[in.nextInt()]+=in.nextFloat(); 9 } 10 K=in.nextInt(); 11 for(int i=0;i<K;i++){ 12 coffi[in.nextInt()]+=in.nextFloat(); 13 } 14 int count=0; 15 StringBuilder sb=new StringBuilder(); 16 for(int i=coffi.length-1;i>=0;i--){ 17 if(coffi[i]!=0){ //May be Math.abs(coffi[i])>=0.05 is better 18 count++; 19 sb.append(String.format(" %d %.1f",i,coffi[i])); 20 } 21 } 22 System.out.println(count+sb.toString()); 23 24 25 } 26 }