原题: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:
where K is the number of nonzero terms in the polynomial,
and
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,
.
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;
}