原题
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:
K N1 aN1 N2 aN2 … NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤1000.
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
题目意思:给定A、B两个多项式,要你计算A + B
输入:每个输入包括两行,每一行包含一个多项式的信息,K N1 aN1 N2 aN2 ... NK aNK
K表示多项式中的非零项的个数,Ni表示指数,aNi表示系数。
输出:对于每个测试案列应该按照输入方式一样输出多项式A+B的值,注意在末尾没有额外的空格。请精确到小数点后一位。
题解
这个题目也不怎么难,需要注意的是系数在后面就好了。
思路
定义个降序排序的map,输入第一个多项式时,自己插入到map里面,输入第二个多项式时,要是mp键的值不为0,就加上系数,要是为0,说明没有同类项,就插入到map里面。
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
// 默认的map是按照升序排序的,加上greater就是按照int键进行降序排序了。
map<int, float, greater<int>> mp;
int n, m, exp;
float coe;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> exp >> coe;
mp[exp] = coe;
}
cin >> m;
for (int i = 0; i < m; ++i) {
cin >> exp >> coe;
if (mp[exp] == 0) {
mp[exp] = coe;
} else {
mp[exp] = mp[exp] + coe;
}
}
int ans = 0;
map<int, float>::iterator it;
for (it = mp.begin(); it != mp.end(); ++it) {
if (fabs(it->second - 0.0) > 0.000001) {
++ans;
}
}
cout << ans;
for (it = mp.begin(); it != mp.end(); ++it) {
if (fabs(it->second - 0.0) < 0.000001) {
continue;
}
// cout << " " << it->first << " " << it->second;
// 注意输出格式,一位小数,末尾不能有空格!!!
printf(" %d %.1f", it->first, it->second);
}
cout << endl;
return 0;
}