PAT A1002 A+B for Polynomials
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
word | meaning |
---|---|
polynomials | n. 多项式 |
nonzero terms | 非零项 |
exponent | n.指数 |
coefficient | n. 系数 |
decimal place | 小数位 |
-
思路1:
用一个数组,下标i表示多项式对应指数项,循环输入两次,累加每一项的系数,最后遍历数组,就得到了结果 -
code1:
#include <stdio.h>
#include <cstring>
const int maxn = 1111;
double ans[maxn];
int main(){
int n, e, cnt = 0;
double c;
memset(ans, 0, sizeof(ans));
for(int i = 0; i < 2; ++i){
scanf("%d", &n);
for(int j = 0; j < n; ++j){
scanf("%d %lf", &e, &c);
ans[e] += c;
}
}
for(int i = 0; i < maxn; ++i){
if(ans[i] != 0) cnt++;
}
printf("%d", cnt);
for(int i = maxn-1; i >= 0; --i){
//!!!:又忘了--
if(ans[i] != 0){
printf(" %d %.1lf", i, ans[i]); //!!!:主要输出格式
// if(i != 0) printf(" "); //这个条件不对,有可能最后一位不是0
}
}
}
- code:Map实现
#include <bits/stdc++.h>
using namespace std;
map<int, double> poly;
int main(){
int n, ex;
double co;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d %lf", &ex, &co);
poly[ex] = co;
}
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d %lf", &ex, &co);
poly[ex] += co;
if(poly[ex] == 0) poly.erase(ex); //Wrong 1:要将系数和为0的项消去(样例3~6)
}
printf("%d", poly.size());
for(auto it = poly.rbegin(); it != poly.rend(); ++it){
printf(" %d %.1f", it->first, it->second);
}
return 0;
}