0
点赞
收藏
分享

微信扫一扫

【PAT甲】1002 A+B for Polynomials (25分)(多项式相加)

舍予兄 2023-04-04 阅读 41


problem

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 N
1
a
N
1

N
2
a
N
2

… N
K
a
N
K

where K is the number of nonzero terms in the polynomial, N
i
and a
N
i

(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N
K
<⋯<N
2
<N
1
≤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

  • 将两个多项式相加,输出一个多项式

solution

  • 题目范围只有1000,所以最多a0到a1000。多项式系数可以为小数,所以开个double a[1000]模拟即可。
  • 一些优化:可以mn和mx记录最小值最大值就不用遍历1000,可以输入时加个特判if(a[i]!=0)记录有几个就不用统计1000,不过数据小懒得优化了。
  • 注意输出格式要求末位不能有空格(包括最后一个点,答案为0时末位也不能有空格)

#include<iostream>
#include<cstdio>
using namespace std;
double a[1010];
int main(){
	
	int k1, k2;
	cin>>k1;
	for(int i = 1; i <= k1; i++){
		int x; double y; cin>>x>>y;
		a[x] += y;
	}
	cin>>k2;
	for(int i = 1; i <= k2; i++){
		int x; double y; cin>>x>>y;
		a[x] += y;
	}
	
	int cnt = 0;
	for(int i = 1000; i >= 0; i--){
		if(a[i] != 0)cnt++;
	}
	if(cnt!=0)cout<<cnt<<' ';
	else cout<<cnt;
	
	int tmp = 0;
	for(int i = 1000; i >= 0; i--){
		if(a[i] != 0){
			tmp++;
			if(tmp == cnt){
				printf("%d %.1lf",i,a[i]);
				break;
			}
			printf("%d %.1lf ",i,a[i]);
		}
	}
	return 0;
}


举报

相关推荐

0 条评论