1009. Product of 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 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 Input2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output
3 3 3.6 2 6.0 1 1.6
代码:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
using namespace std;
ifstream fin("in.txt");
#define cin fin
struct Term
{
int index;
double val;
Term(){}
Term(int ind,double v){index = ind;val = v;}
};
int main()
{
int an,index,bn;
cin>>an;
Term *A = new Term[an];
int i;
for(i=0;i<an;i++)
{
cin>>A[i].index>>A[i].val;
}
cin>>bn;
Term *B = new Term[bn];
for(i=0;i<an;i++)
{
cin>>B[i].index>>B[i].val;
}
int maxlen = A[0].index+B[0].index + 1;
double *res = new double[maxlen];
memset(res,0,sizeof(double)*(maxlen));
int j;
for(i=0;i<an;i++)
{
for(j=0;j<bn;j++)
{
index = A[i].index+B[j].index;
res[index] = res[index] + A[i].val * B[j].val;
}
}
stringstream stream;
int count = 0;
for(i=maxlen-1;i>=0;i--)
{
if(res[i]!=0.0f)
{
stream<<' '<<i<<' '<<setiosflags(ios::fixed)<<setprecision(1)<<res[i];
count++;
}
}
cout<<count<<stream.str()<<endl;
system( "PAUSE");
return 0;
}
悲催的是,最后一个case通过不了,对比下他人的代码也没发现自己啥问题。如果谁发现了我的问题,麻烦回复告诉我一声,不胜感激!