2020.02.20,对map键值和迭代器的复习,可应用于两个数据有所联系时的题目
1002 A+B for Polynomials (25分)
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
说实话第一眼看这个题目的时候就有几个单词看不太懂,然后查了一会儿单词才弄懂题意。。。(英语还是很重要的),一开始也没有看懂是怎么得出这个结果的(数学也没太学好。。。),最后在草稿纸上折腾很久后终于弄懂了(谢谢来自小象的制图!!!)
多项式中的单项式系数相同的话就指数相加!!!输出的时候需要对非0项的个数统计
解题首先想到将系数和指数结对,可以使用结构体也可以使用二维数组,这里使用的是map,每次使用count()函数检验是否已存在该系数,若已存在该系数时,则只需要将指数相加更新即可,遇到系数为0的项需要特判剔除,最后使用,fixed()浮点数输出, setprecision()保留一位小数进行输出
对于map的一些补充,map常用于一对元素的映射,而且map本身是递增有序的不需要进行排序
此处的结果是一个浮点数,所以在与0进行比较的时候,最好加上大于等于0.0,和小于等于0.0的双保险(或者是不等于正负0.0),以免题目在精度上面挖坑
#include<iostream>
#include<iomanip>
#include<map>
/*
2 1 2.4 0 3.2
2 2 1.5 1 0.5
*/
using namespace std;
#define N 2
int main(){
int k ,temp1;
double temp2;
map<int , double> comb;//创建字典存入指数和系数
int finalcount = 0;
for(int i = 1;i <= 2;i++){
cin >> k;
for(int j = 0;j < k;j++){
cin >> temp1 >> temp2;
if(comb.count(temp1) == 0){
comb[temp1] = temp2;
}else{
comb[temp1] += temp2;
}
}
}
for(map<int , double>::const_iterator iter = comb.begin();iter != comb.end() ; iter++){
if(iter->second != 0.0){
finalcount++;
}
}
cout << finalcount;
for(map<int , double>::reverse_iterator iter = comb.rbegin();iter != comb.rend() ; iter++){
if(iter->second != 0.0 && iter->second != -0.0){
cout << " " <<iter->first << " " << fixed << setprecision(1) <<iter->second;
}
}
return 0;
}
注意这里在遍历的时候使用的是迭代器,在进行统计的时候使用const_iterator,可以保证数据不会被改变,在输出的时候将多项式系数大的项放在前面,刚好和map的下标逆向,所以使用逆向迭代器,注意迭代器的始末位置要更改为
for(map<int , double>::reverse_iterator iter = comb.rbegin();iter != comb.rend() ; iter++)
当然,一般觉得写这一大串容错率比较低,所以在C++11中可以使用auto自动类型识别begin(),还是rbegin()来选择正逆向迭代器
for(auto iter = comb.rbegin();iter != comb.rend() ; iter++)