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
注意點(diǎn):
- coefficients可以是負(fù)數(shù)
- 系數(shù)為0不進(jìn)行輸出
- 如果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) // 兩個(gè)系數(shù)和為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;
}