This time, you are supposed to find A+B where A and B are two polynomials.
Input
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~ … NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.
Output
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
题目大意:计算 A + B,A 和 B 是两个多项式。
K N1 aN1…Nk aNk
K - 非零项的个数
Ni - 指数
aNi - 系数
注意每行的末尾没有额外的空格。保留一位小数。
数据范围:1 <= K <= 10,0 <= Nk < … < N2 < N1 <=1000
aNi没有给范围???
解题思路:用结构体保存每一项。循环检查,指数相等的系数加到 A,B 中指数置 -1表示加过,结束后把 B 中指数非 -1 的项加到 A 后面。然后把 A 中系数为 0 的项指数置 -1 表示没有该项。最后根据指数从大到小排序,输出。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100+10;
const int INF = 0x3f3f3f3f;
struct Node {
int zs;
double xs;
}A[30], B[30];
bool cmp(Node a, Node b) {
return a.zs > b.zs;
}
int main() {
int n1, n2;
scanf("%d", &n1);
for (int i = 0; i < n1; i++) {
scanf("%d%lf", &A[i].zs, &A[i].xs);
}
scanf("%d", &n2);
for (int i = 0; i < n2; i++) {
scanf("%d%lf", &B[i].zs, &B[i].xs);
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (A[i].zs == B[j].zs) {
A[i].xs += B[j].xs;
B[j].zs = -1;
}
}
}
for (int i = 0; i < n2; i++) {
if (B[i].zs != -1) {
A[n1].zs = B[i].zs;
A[n1++].xs = B[i].xs;
}
}
int cnt = 0;
for (int i = 0; i < n1; i++)
if (A[i].xs == 0)
A[i].zs = -1;
for (int i = 0; i < n1; i++)
if (A[i].zs != -1) cnt++;
sort(A, A+n1, cmp);
printf("%d", cnt);
for (int i = 0; i < cnt; i++) {
printf(" %d %.1lf", A[i].zs, A[i].xs);
}
printf("\n");
return 0;
}
提交时间 | 状态 | 分数 | 题目 | 编译器 | 耗时 |
---|---|---|---|---|---|
2018/7/5 22:38:55 | 答案正确 | 25 | 1002 | C++ (g++) | 3 ms |
2018/7/5 22:33:21 | 部分正确 | 17 | 1002 | C++ (g++) | 3 ms |
2018/7/5 22:24:19 | 部分正确 | 17 | 1002 | C++ (g++) | 3 ms |
2018/7/5 22:23:34 | 部分正确 | 17 | 1002 | C++ (g++) | 2 ms |
没注意到相加后可能出现系数为 0 的项,WA了几个