java_patest甲级真题1002. A+B for Polynomials

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

import java.util.Scanner;
public class Main
{
	public static void main(String[] args)
        {
        	Scanner scanner = new Scanner(System.in);
          	String str1 = scanner.nextLine();
          	String str2 = scanner.nextLine();
          	String[] temp1 = str1.split(" ");
          	String[] temp2 = str2.split(" ");
          	float[] fA = new float[temp1.length] ;
          	float[] fB = new float[temp2.length];
          	for(int i = 0 ; ifB[j])
	                        {
	                        	sb.append((" "+(int)fA[i]+" "+fA[i+1]));
	                        	i = i +2;
	                        }else
	                        {
	                        	sb.append((" "+(int)fB[j]+" "+fB[j+1]));
	                        	j = j +2 ;
	                        }
                  	count++;
                }
          	sb.insert(0,count);
          	String string = new String(sb);
          	String[] s = string.split(" ");
          	System.out.print(Integer.parseInt(s[0]));
          	for(int k =1 ; k< s.length ;k +=2)
          	{
          		System.out.print(" "+s[k] +" ");
          		System.out.printf("%.1f",Float.parseFloat(s[k+1]));
          	}
        }
}

本题分析: 这道题要求是 A B两个多项式想加,一道很简单的题,但是有个坑 神坑···如果两个数相加 系数刚好抵消掉,那就呵呵了。 所以被这个坑了起码四五次。

当知道了原因后 就好办。 题目分析: 首先 这道题 A B 两个 都是 有顺序的 N值是递减的,所以 每次比较都可以先比较下,如果A的大 那么就把A 加进去,然后A的指针往后移动,如果B 那就加B,如果相同,先把数值相加·然后加进去,当然 如果相同的情况还要判断 是否为0 ;

其次 : 

重要: 这道题 可以还有另外两种,第一种: 看这题··首先想到 如果用容器做的话 ,第一 用MAP 可以实现,第二 用list 的话 那么只要构建对象就能实现。 

你可能感兴趣的:(java_patest甲级真题)