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

大意:

程序输入为两行:均为一个多项式,按 K N1 An1 N2 An2......Nk Ank,K代表的是多项式的非零项数,范围闭区间是[1,10],N1到Nk的范围区间是 1<= Nk <= ......<= N1 <= 1000;

Nk是指数,Ank是系数,遇到相同的指数,系数进行累加,从而合并成一个多项式。

例子输入:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

可以解析成:

第一行: 2个子项---1*2.4 + 0*3.2

第二行: 2个子项---2*1.5 + 1*0.5

其中指数部分,二者有重合,可以累加,结果有 1*(2.4 + 0.5)

输出:

3 2 1.5 1 2.9 0 3.2

可以理解成: 3个子项---2*1.5 + 1*2.9 + 0*3.2


思路:建立一个长度为最长范围的数组c,c[zs]=xs;(zs:指数 xs=系数),接受a,b数据的同时存入数组c中,统计数组中不为0的项数,然后反向输出所有不为0的指数和系数。

代码:

import java.util.Scanner;

public class b1002 {
	public static void main(String[] args){
		int m,n;
		int xs;
		float zs;
		float[] c=new float[1001];
		Scanner in=new Scanner(System.in);
		m=in.nextInt();
		for(int i=0;i<m;i++){
			xs=in.nextInt();
			zs=in.nextFloat();
			c[xs]=zs;
		}
		n=in.nextInt();
		for(int i=0;i<n;i++){
			xs=in.nextInt();
			zs=in.nextFloat();
			c[xs]+=zs;
		}
		int s=0;
		for(int i=0;i<c.length;i++){
			if(c[i]!=0.0)s++;
		}
		System.out.printf("%d",s);
		for(int i=1000;i>=0;i--){
			if(c[i]!=0.0)
			System.out.printf(" %d %.1f",i,c[i]);
		}
		
		
	}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值