(PAT Advanced Level) 1002.A+B for Polynomials(多项式模拟) C++

原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

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 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 N_{i} and a N i 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 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

题目分析:
暴力求解,用两个1000维的数组存储多项式A和B的系数(下标表示指数),然后逐一相加,最后输出非零项。

#include <iostream>

using namespace std;

int main() {
	int k1, k2;
	double poly1[1001] = { 0 };
	double poly2[1001] = { 0 }; // 两个多项式数组,存储系数
	cin >> k1;
	int n; // 指数
	int i;
	for (i = 0; i < k1;i++) {
		cin >> n;
		cin >> poly1[n];
	}
	cin >> k2;
	for (i = 0; i < k2;i++) {
		cin >> n;
		cin >> poly2[n];
	}
	// 错误点,加和之后,可能为0
	int count = 0;
	for (i = 0; i < 1001; i++) {
		if (poly1[i] || poly2[i]) {
			poly1[i] += poly2[i];
			if (poly1[i]) count++;
		}
	}
	cout << count;
	for (i = 1000; i >= 0 && count; i--) {
		if (poly1[i]) {
			count--;
			printf(" %d %.1f",i,poly1[i]);
		}
	}

	system("pause");
	return 0;
}

但是,其实只需要一个数组存储就够了,到时候边读入边处理。

#include <iostream>

using namespace std;

int main() {
	int k1, k2;
	double poly[1001] = { 0 };
	int n;
	double num;
	cin >> k1;
	while (k1--) {
		cin >> n;
		cin >> num;
		poly[n] += num;
	}
	cin >> k2;
	while (k2--) {
		cin >> n;
		cin >> num;
		poly[n] += num;
	}
	int count = 0;
	for (int i = 0; i <= 1000; i++) {
		if (poly[i]) count++;
	}
	cout << count;
	for (int i = 1000; i >= 0; i--) {
		if (poly[i]) printf(" %d %.1f", i, poly[i]);
	}

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Africa_South/article/details/88795598