This time, you are supposed to find A+B where A and B are two polynomials(多項式).html
Inputios
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.數組
Outputspa
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.code
Sample Inputorm
2 1 2.4 0 3.2
2 2 1.5 1 0.5htm
Sample Outputblog
3 2 1.5 1 2.9 0 3.2ci
題目意思:兩個多項式的相加,每一行第一個數k表示非零係數的個數,以後是每一個非零係數的指數和係數。get
解題思路:能夠直接使用數組來模擬,這裏我使用map複習一下map的用法。
http://www.javashuo.com/article/p-hrodfqku-x.html
#include<iostream> #include<algorithm> #include<string> #include<cstdio> #include<map> using namespace std; int main() { int T=2; int n,k,i; double m; int cnt=0; map<int,double>mp; map<int,double>::iterator it;//迭代器 map<int,double>::reverse_iterator rit;//反向迭代器 while(T--) { scanf("%d",&k); for(i=0; i<k; i++) { scanf("%d%lf",&n,&m);//n爲指數,m爲係數 mp[n]+=m; } } for(it=mp.begin();it!=mp.end();it++)//係數爲0的 { if(it->second!=0) { cnt++; //printf("%lf\n",it->second); } } printf("%d",cnt); //map默認從小到大,能夠用逆向迭代器逆序輸出 for(rit=mp.rbegin();rit!=mp.rend();rit++)//係數爲0的 { if(rit->second!=0) { printf(" %d %.1f",rit->first,rit->second); } } printf("\n"); return 0; }