1002 A+B for Polynomials (25 分)
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
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 Specification:
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
简单翻译:拿输入的例子第一行来说,第一个数2表示这个多项式有两项,第二个数1和第三个数2.4分别表示第一项的指数和系数,指数的范围是0-1000,第四个和第五个与第二和第三同理。
分析:数据结构采用数组a[]存储,a[i]表示指数为i的多项式系数为a[i]。由于以指数为下标可以不用考虑指数相同,读取第二行的多项式直接把系数加在第一个的基础上,最后只需要考虑输出空格的问题。
坑:1:空格的格式问题(最后不能有空格);2:范围的问题(数组设置为a[1000]);
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
/*两个多项式相加*/
Scanner input = new Scanner(System.in) ;
double a[] = new double[1001] ;//a[i]存放指数为i的多项式的项数
int i ;
for(i=0; i<=1000; i++){
a[i] = 0 ;
}
int c ;
double d ;
int m = input.nextInt() ;
for(i=0; i<m; i++){
c = input.nextInt() ; //读指数
d = input.nextDouble() ; //读项数System.out.println(123);
a[c] = d ;
}
int n = input.nextInt() ;
for(i=0; i<n; i++){
c = input.nextInt() ;
d = input.nextDouble() ;
a[c] += d ;
}
int count = 0 ;
for(i=0; i<=1000; i++){ //统计非零项
if(a[i] != 0){
count++ ;
}
}
if(count == 0){
System.out.printf("%d", 0) ;
}
else {
System.out.printf("%d ", count) ;
}
for(i=1000; i>=0; i--){
if(a[i] != 0 && count > 0){
System.out.printf("%d %.1f", i,a[i]) ;
count-- ;
if(count >= 1){
System.out.printf(" ") ;
}
}
}
}
}