PAT 甲级 1001 A+B Format (20 分)(Java)
题目
注意事项
- 系数保留一位小数;
- 最后一位数字后面没有空格;
解法
解法一
开一个足够大的数组,下标即是指数,数组中存的是系数,初始化为0.0,然后将两个数组按照相应的指数项将系数存入数组,然后判断数组中有多少项,然后依次输出;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int e;
double c;
int index = 0;
double[] res = new double[1005];
Arrays.fill(res, 0.0);
int m = sc.nextInt();
for(int i=0; i<m; ++i){
e = sc.nextInt();
c = sc.nextDouble();
res[e] += c;
}
int n = sc.nextInt();
for(int i=0; i<n; ++i){
e = sc.nextInt();
c = sc.nextDouble();
res[e] += c;
}
int total = 0;
for(int i=0; i < 1005; ++i){
if(res[i] != 0.0){
total++;
}
}
System.out.print(total);
for(int i=1004; i>=0; --i){
if(res[i] != 0.0){
System.out.print(" " + i + " " + String.format("%.1f", res[i]));
}
}
}
}