a1002 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

Title:

1. Enter a total of two lines, each line represents a polynomial

2. In each row, the first number K is the number of non-zero terms of the polynomial, the next K groups of numbers (N1, a1), N1 represents the index of the term, and a1 represents the coefficient of the term

3. The output form is required to be the same as the input form


Ideas:

1. Use map to store each item, the key is the index, and the value is the coefficient.


note:

1. The output is sorted by index from largest to smallest

2. Keep one decimal place for the coefficient

3. If the coefficient is 0, there is no need to output, it may involve test points 3-6

4. If you use cout output, pay attention to setprecision will carry out

5. If the coefficients are all 0, just output 0, which may cause a segmentation fault at test point 6.

6. Use map to perform two traversals when judging whether the coefficient is 0, and the erase operation cannot be used when the coefficient is 0, and the first number output is not necessarily map.size()


doubt:

1. Does the index have to be an integer? The code of the goddess is also processed according to int, the double storage I used when writing, but the decimal place was still removed when submitting. .


ac code:

#include<iostream>
#include<map>
#include<iomanip>
using namespace std;
map<double,double> m;
int main() {
	int a,count=0;
	double b,c;
	for(int i=0; i<2; i++) {
		cin>>a;
		while(a--) {
			cin>>b>>c;
			if(m.find(b)!=m.end()) {
				m[b]+=c;
			} else {
				m[b]=c;
			}
		}
	}
	for(auto it=m.begin(); it!=m.end(); it++) {
		if(it->second!=0) {
			count++;
		}
	}
	cout<<count;
	for(auto it=m.rbegin(); it!=m.rend(); it++) {
		if(it->second!=0) {
			printf(" %.0f %.1f",it->first,it->second);
// 		cout<<" "<<setiosflags(ios::fixed)<<setprecision(0)<<it->first<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<it->second;
		}
	}
}

 

Guess you like

Origin blog.csdn.net/qq_34401933/article/details/114122220