PAT A 1002. A+B for Polynomials

来源:互联网 发布:linux 进入sql 编辑:程序博客网 时间:2024/04/28 11:03

原题:

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 Pat1002{  public static void main(String args[]){    Scanner input = new Scanner(System.in);     int n = input.nextInt();    int[] a1 = new int[n];    double[] a2 =  new double[n];    for (int i = 0; i < n; i++){        a1[i] = input.nextInt();        a2[i] = input.nextDouble();    }    int m = input.nextInt();    int[] b1 = new int[m];    double[] b2 =  new double[m];    for (int i = 0; i < m; i++){        b1[i] = input.nextInt();        b2[i] = input.nextDouble();    }    int i = 0;    int j = 0;    int count = 0;    int count1 = a1[i];    int count2 = b1[j];    String c = "";    while(count1 != -1 || count2 != -1){        if (count1 > count2){            c = c + " " + count1 + " " + Math.round(a2[i] * 10) / 10.0; //保留一位小数            count++;             if (i < a1.length - 1)                count1 = a1[++i];            else                count1 = -1;        }        else if (count1 < count2){            c = c + " " + count2 + " " + Math.round(b2[j] * 10) / 10.0;            count++;             if (j < b1.length - 1)                count2 = b1[++j];            else                count2 = -1;        }        else{            double sum = Math.round(((a2[i] + b2[j]) * 10)) / 10.0;            if (sum != 0){      //某项被消除的情况                c = c + " " + count1 + " " + sum;                count++;             }            if (i < a1.length - 1)                count1 = a1[++i];            else                count1 = -1;            if (j < b1.length - 1)                count2 = b1[++j];            else                count2 = -1;        }    }    if (c == "") //相加为0的情况        c = "0";    else        c = count + c;    System.out.print(c);    input.close();  }}
0 0
原创粉丝点击