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
这道题的解题思路和前面多项式加减法的思路是相同的,需要注意的地方就是,在多项式中的两个元素相乘的时候,对应的是指数相加,系数相乘。
将计算结果保留到额外申请的结构体变量中,然后将这个结构体变量加入到额外申请的一个 list 中。
在node插入到 list 之前,先需要对list 中的各个元素进行扫描一遍,如果遇到有指数相同的结点,与之进行系数的加和操作,
如果加和的结果为 0 则将该节点与list 中的最后的元素node 结构体中的元素属性进行互换,然后通过 vector 中的pop_back() 操作将元素从
list 中进行删除。如果没有指数相同的元素节点的话,则将新得到的结点安置在list 的队尾,
在最后所有结构体对应的元素相乘之后, 对list 的更新操作停止,此时通过重载运算符号,对list 中的元素进行排序,
即可得到 list1 list2 中所有元素结点相乘的结果 list , 并且 list 的 size() 属性值,即为多项式中常数项系数非零元素的个数。
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#define MAXN 1001
using namespace std ;
struct node
{
double A ;
int base ;
node(double a , int b )
{
A = a ;
base = b ;
}
node () {}
bool operator < ( const node &b ) const
{
if (base < b.base )
{
return false ;
}
else
return true ;
}
} ;
vector<node> list ;
void calculate( node a , node b )
{
bool findMatch = false ; //如果在list 中找到与新插入的结点指数base 相同的结点之后,findMatch = true
double result ;
node x(a.A*b.A, a.base+b.base) ;
for ( int i = 0 ; i < list.size () ; i++ )
{
if ( x.base == list[i].base )
{
result = x.A + list[i].A ;
if ( fabs(result) < 1e-15)
{
//swap with the last one , then pop_back()
list[i].base = list[list.size()-1].base ;
list[i].A = list[list.size() -1].A ;
list.pop_back() ;
}
else
{
list[i].A += x.A ;
}
findMatch = true ;
}
}
if ( !findMatch )
{
list.push_back( x ) ;
}
}
int main ( void )
{
vector<node> list1 , list2 ;
int k , b;
double a ;
scanf("%d", &k ) ;
for( int i = 0 ; i < k ; i++ )
{
scanf("%d%lf", &b , &a ) ;
list1.push_back(node ( a , b )) ;
}
scanf("%d", &k ) ;
for ( int i = 0 ; i < k ; i++ )
{
scanf("%d%lf", &b , &a) ;
list2.push_back(node (a, b )) ;
}
for (int i = 0 ; i < list1.size() ; i++ )
{
for ( int j = 0 ; j < list2.size() ; j++ )
{
calculate ( list1[i] , list2[j] ) ;
}
}
sort ( list.begin() , list.end() ) ;
printf("%d ", list.size() ) ;
for ( int i = 0 ; i < list.size() ; i++ )
{
printf("%d %.1lf", list[i].base , list[i].A ) ;
if ( i != list.size() -1 )
{
printf(" ") ;
}
}
//system("pause") ;
return 0 ;
}