PAT甲级刷题记录——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 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<⋯2​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,1000]的,而且输出的时候也要按着指数的大小来输出(注意,这里是倒序),所以直接用数组下标代表指数,其值代表系数存储就好了,然后每次读入n和an(n是指数,an是系数),就给对应p[n]+=an,这样的话,只要p[n]不为0,就代表着是一个非零项,于是cnt++(因为最后要输出所有非零项的总数),最后再倒着遍历数组输出指数和系数就可以了。
为了尽量减少耗时,我建议在读入的时候记录最高的指数(我这里用了maxi),这样直接i=maxi一直到i=0逆序遍历数组输出即可。

代码

#include 
#include
#include
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;
}

你可能感兴趣的:(PAT甲级)