PAT Grade A Brush Test Record-1002 A + B for Polynomials (25 points)

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 N1 aN1 N​2 aN2 … NK aNK
​​where K is the number of nonzero terms in the polynomial, N​iand a​Ni(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

Ideas

This question is also very simple, because the index strictly abides by [0,1000], and the output should also be output according to the size of the index (note that here is the reverse order), so directly use the array index to represent the index The value represents that the coefficient is stored, then each time n and an are read in (n is an exponent, an is a coefficient), the corresponding p [n] + = an is given. In this case, as long as p [n] is not 0, then Represents a non-zero item, so cnt ++ (because the total number of all non-zero items is output at the end), and finally traverse the array backwards to output the index and coefficient.
In order to minimize the time-consuming, I suggest to record the highest index when reading (I used maxi here), so that i = maxi directly until i = 0 traverse the array output in reverse order.

Code

#include<cstdio> 
#include<string>
#include<iostream>
using namespace std;
const int maxn = 1001;
double p[maxn]={0};//初始化所有系数是0 
int main(){
	int maxi = 0;
	int k1;
	scanf("%d", &k1);
	while(k1--){
		int n;
		double an;
		scanf("%d%lf", &n, &an);
		p[n] += an;//下标是指数,值是系数
		if(n>maxi) maxi = n;
	}
	int k2;
	scanf("%d", &k2);
	while(k2--){
		int n;
		double an;
		scanf("%d%lf", &n, &an);
		p[n] += an;
		if(n>maxi) maxi = n;
	}
	int cnt = 0;
	for(int i=0;i<=maxi;i++){
		if(p[i]!=0) cnt++;
	}
	printf("%d", cnt);
	for(int i=maxi;i>=0;i--){
		if(p[i]!=0){
			printf(" %d %.1f", i, p[i]);
		}
	}
    return 0;
}
Published 54 original articles · won 27 · views 4972

Guess you like

Origin blog.csdn.net/weixin_42257812/article/details/105589372