This time, you are supposed to find A+B where A and B are two polynomials.
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.
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.
思路1:
题目要求的是多项式的和,并输出所有系数非零的多项式数目,以及按照指数从大到小的顺序输出多项式每一项的指数和系数。首先可以考虑建立一个map映射,将多项式的指数和系数对应起来。输入第一组数据的时候可以直接建立映射,并且建立一个布尔型的hashTable[],用来记录已经出现过的指数,再输入第二组数据的时候,如果输入的指数之前已经存在了,那么就需要将指数对应的系数在原来的基础上加上后面输入的系数,如果输入的指数之前没有出现过那么就建立新的指数和系数的映射。输出数据的时候由于map会按照键的值从小到达输出,那么我们需要利用反向迭代器map<int,float>::reverse_iterator it来从后往前输出,起点为mp.rbegin()(包含),终点为mp.rend()(不包含)。
代码:
#include <iostream> #include<map> using namespace std; map<int, float>mp; bool hashTable[1010] = { false }; int main() { int n1, n2, N; float a; scanf("%d", &n1); for (int i = 0; i < n1; i++) { scanf("%d %f", &N, &a); mp[N] = a; hashTable[N] = true; } scanf("%d", &n2); for (int i = 0; i < n2; i++) { scanf("%d %f", &N, &a); if (hashTable[N] == true) mp[N] += a; else mp[N] = a; } map<int, float>::iterator ip; map<int, float>::reverse_iterator it; int len = mp.size(); int count = 0; for (ip = mp.begin(); ip != mp.end(); ip++) { if ((int)ip->second != 0) count++; } printf("%d", count); for (it = mp.rbegin(); it != mp.rend(); it++) { if ((int)it->second != 0) printf(" %d %.1f", it->first, it->second); } return 0; }思路2:
设立a数组,⻓度为指数的最大值,a[i] = j表示指数i的系数为j,接收a和b输入的同时将对应指数 的系数加入到a中,累计a中所有非零系数的个数,然后从后往前输出所有系数不为0的指数和系数。
代码:
#include <iostream> using namespace std; int main() { float a[1010] = { 0 }; int m, n, t; float num; scanf_s("%d", &n); for (int i = 0; i < n; i++) { scanf_s("%d%f", &t, &num); a[t] += num; } scanf_s("%d", &m); for (int i = 0; i < m; i++) { scanf_s("%d%f", &t, &num); a[t] += num; } int count = 0; for (int i = 0; i < 1010; i++) { if ((int)a[i] != 0) count++; } printf_s("%d", count); for (int i = 1009; i >= 0; i--) { if ((int)a[i] != 0) printf_s(" %d %.1f", i, a[i]); } return 0; }