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
题意:
1.一共输入两行,每行表示一个多项式
2.每行中,第一个数字K为该多项式的非0项项数,接下来K组数字(N1,a1),N1表示该项的指数,a1表示该项系数
3.要求输出形式与输入形式相同
思路:
1.使用map存储每一项,key为指数,value为系数。
注意:
1.输出按指数从大到小排列
2.系数保留一位小数
3.如果系数为0,就不用输出了,可能涉及测试点3-6
4.如果使用cout输出,注意setprecision会进行进位
5.如果系数全为0,只输出0就可以了,这里可能导致测试点6的段错误
6.使用map在判断系数是否为0时要进行两次遍历,且不能当系数为0时使用erase操作,输出的第一个数字不一定为map.size()
疑问:
1.指数一定是整数吗?女神的代码也是按照int来处理的,我在编写时使用的double存储,不过提交时还是把小数位去掉了。。
ac代码:
#include<iostream>
#include<map>
#include<iomanip>
using namespace std;
map<double,double> m;
int main() {
int a,count=0;
double b,c;
for(int i=0; i<2; i++) {
cin>>a;
while(a--) {
cin>>b>>c;
if(m.find(b)!=m.end()) {
m[b]+=c;
} else {
m[b]=c;
}
}
}
for(auto it=m.begin(); it!=m.end(); it++) {
if(it->second!=0) {
count++;
}
}
cout<<count;
for(auto it=m.rbegin(); it!=m.rend(); it++) {
if(it->second!=0) {
printf(" %.0f %.1f",it->first,it->second);
// cout<<" "<<setiosflags(ios::fixed)<<setprecision(0)<<it->first<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<it->second;
}
}
}