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

 Problem-solving ideas: the idea is not difficult, there are several attention points (① output items can only be non-zero entries, so be sure not to store coefficient term 0, but also to pay attention to the same power of positive and negative coefficients relative to eliminate 0, in which case the input may be increased if a judgment to solve; ② when the last non-zero entries obtained by summing the number is 0, the output format to be noted that no line breaks plus spaces) ** test sample code below The first case to test **

code show as below:

#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

 

Published 18 original articles · won praise 1 · views 987

Guess you like

Origin blog.csdn.net/qq_38969094/article/details/104319145