A+B for Polynomials (25 分)
题目描述:
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: , where K is the number of nonzero terms in the polynomial, and are the exponents and coefficients, respectively. It is given that .
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
注意点:
- coefficients可以是负数
- 系数为0不进行输出
- 如果size为0,直接输出0
- 最后没有空格
#include<iostream>
#include<map>
#include<vector>
using namespace std;
map<int, float> poly1;
int main() {
for (int i = 0; i < 2; ++i)
{
int n1;
scanf("%d", &n1);
for (int i = 0; i < n1; ++i)
{
int exp;
float cof;
scanf("%d%f", &exp, &cof);
poly1[exp] += cof;
}
}
vector<pair<int, float> > res;
for(map<int, float>::reverse_iterator it = poly1.rbegin(); it != poly1.rend(); it++) {
if(it->second != 0) // 两个系数和为0的得过滤掉
res.push_back(make_pair(it->first, it->second));
}
printf("%lu", res.size());
for (int i = 0; i < res.size(); ++i)
{
printf(" %d %.1f", res[i].first, res[i].second);
}
return 0;
}
网友评论