PAT 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​​<⋯

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


输入输出都是降幂排列
多项式指的是2.4*x^1+3.2*x^0     不是2.4^1+3.2^0   心不在焉的。。。唉。。
系数为0的不输出

第一次麻烦代码:

#include
#include
using namespace std;

struct Pol
{
	int n;double a;
}A[11], B[11], C[11];

int main() {
	// freopen("input.txt", "r", stdin);
	int k1, k2;
	cin >> k1;
	for (int i = 0;i> A[i].n >> A[i].a;
	}
	cin >> k2;
	for (int i = 0;i> B[i].n >> B[i].a;
	}

	int index = 0, ia = 0, ib = 0;
	while (iaB[ib].n
			C[index].n = A[ia].n;
			C[index++].a = A[ia++].a;
		}
	}

	while (ia

方法二:
脑子长期不用会锈掉的
本题指数最大1000 完全可以牺牲空间地来做  1000太小了  时间也浪费不了多少。。。 
 

#include
#include
using namespace std;
int main() {
	// freopen("input.txt", "r", stdin);
	double a,A[1001] = { 0 };
	int n,k, count = 0;
	cin >> k;
	while (k--) { 
		cin >> n >> a;
		A[n] += a; 
	}
	cin >> k;
	while (k--) { 
		cin >> n >> a;
		A[n] += a; 
	}
	for (int i = 0;i <= 1000;i++) if (A[i] != 0) count++;
	cout << count;
	for (int i = 1000;i >= 0;i--) {
		if (A[i] != 0) printf(" %d %.1f", i, A[i]);
	}
	return 0;
}

 

你可能感兴趣的:(算法竞赛,PAT)