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 (,) are the exponents and coefficients, respectively. It is given that 1, 0.
Output Specification:
For each test case you should output the product 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 up to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 3 3.6 2 6.0 1 1.6
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct poly{ int expo; double coef; }; void add(vector<poly>& vec,poly po){ for(int i=0;i<vec.size();i++){ if(vec[i].expo==po.expo){ vec[i].coef+=po.coef; if(vec[i].coef==0){ vec.erase(vec.begin()+i); / * * This is necessary to determine the polynomial 0, erase carried out * / } return ; } } IF (! Po.coef = 0 ) vec.push_back (PO); } BOOL CMP (P poly, poly P2) { return P. Expo> p2.expo; } int main () { / * * * Note points * 1 to one decimal * / int M, N; Vector <poly> RES; CIN >> M; poly P [M]; for ( int I = 0 ; I <M; I ++ ) { CIN >> P [I] .expo >>p[i].coef; } cin>>N; poly p2[N]; for(int i=0;i<N;i++){ cin>>p2[i].expo>>p2[i].coef; } for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ poly temp; temp.expo=p[i].expo+p2[j].expo; temp.coef=p[i].coef*p2[j].coef; add(res,temp); } } /**这边需要sort一下*/ sort(res.begin(),res.end(),cmp); cout<<res.size(); for(int i=0;i<res.size();i++){ printf(" %d %.1f",res[i].expo,res[i].coef); } system("pause"); return 0; }
Vector need to remember to delete elements, use the erase (iter *)