原题地址: http://www.patest.cn/contests/pat-a-practise/1002
1002. A+B for Polynomials (25)
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
本题需要注意的地方不多,double保留两位小数的时候,因为浮点数的原因,四舍五入的时候可能会有些出入。代码如下:
package com.dye.pat.t1002;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String str1[] = in.nextLine().split(" ");
String str2[] = in.nextLine().split(" ");
in.close();
int a = Integer.parseInt(str1[0].trim());
int b = Integer.parseInt(str2[0].trim());
int[] ex1 = new int[a];
double[] co1 = new double[a];
int[] ex2 = new int[b];
double[] co2 = new double[b];
for (int i = 0; i < a; i++) {
ex1[i] = Integer.parseInt(str1[2 * i + 1].trim());
co1[i] = Double.parseDouble(str1[2 * i + 2].trim());
}
for (int i = 0; i < b; i++) {
ex2[i] = Integer.parseInt(str2[2*i + 1].trim());
co2[i] = Double.parseDouble(str2[2*i + 2].trim());
}
int max = max(ex1[0], ex2[0]);
double sum[] = new double[max + 1];
for (int i = max; i >= 0; i--) {
sum[i] = 0;
}
for (int i = 0; i < ex1.length; i++) {
sum[ex1[i]] += co1[i];
}
for (int i = 0; i < ex2.length; i++) {
sum[ex2[i]] += co2[i];
}
show(sum, max);
}
public static int max(int a, int b) {
if (a > b) {
return a;
} else
return b;
}
public static void show(double[] a, int n) {
/*
* if(n == 0){ if(a[n] !=0 ) System.out.println("1 0 " + a[n]); else
* System.out.println("0 0 "); return; }
*/
/*
* else if(a[n] == 0){ show(a,n-1); return; }
*/
int t = n + 1;
String re = "";
for (int i = n; i >= 0; i--) {
if (a[i] == 0) {
t--;
continue;
}
double d = a[i];
d=((double)((int)Math.round(d*10)))/10;
// d=((double)((int)(d*10)))/10;
re = re + " " + i + " " + d;
}
if (t == 0)
re = "0";
else
re = t + re;
System.out.println(re.trim());
}
}