PAT 1002 A+B for Polynomials (25分) (C++)

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

 解题思路:思路其实不难,主要有几个注意点(① 输出的项只能是非零项,所以要确保不存储系数为0的项,而且要注意相同幂次项正负系数相消得0,这种情况在输入时可以增加一个if判断来解决;② 当最后求和所得非零项数为0时,输出格式要注意没有空格再加换行符)**代码下方的测试样例可以用来测试第一种情况**

代码如下:

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	scanf("%d",&n);
	map<int,double> num;
	for(int i = 0; i < n; i++){
		int exp;
		double coe;
		scanf("%d %lf",&exp,&coe);
		if(coe != 0) num[exp] += coe;
	}
	int m;
	scanf("%d",&m);
	for(int i = 0; i < m; i++){
		int exp;
		double coe;
		scanf("%d %lf",&exp,&coe);
		num[exp] += coe;
		map<int,double>::iterator it = num.find(exp);
		if(it->second == 0){
			num.erase(it);
		}
	}
	if(num.size() != 0) printf("%d ",num.size());
	else printf("%d\n",num.size());
	for(map<int,double>::iterator it = num.end(); it != num.begin();){
		--it;
		if(it->second != 0){
			if(it == num.begin()) printf("%d %.1lf\n",it->first,it->second);
			else printf("%d %.1lf ",it->first,it->second);
		}

	}
} 
//4 4 0.5 2 5.6 1 -2.7 0 3.6
//3 3 -2.1 2 -5.6 1 2.7
//正确答案:3 4 0.5 3 -2.1 0 3.6
发布了18 篇原创文章 · 获赞 1 · 访问量 987

猜你喜欢

转载自blog.csdn.net/qq_38969094/article/details/104319145