PAT--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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N​K​​<⋯<N​2​​<N​1​​≤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 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 <bits/stdc++.h>

using namespace std;

const int maxn = 1010;


struct Node{
    int exp;
    double coe;
}a[maxn],b[maxn],c[maxn],d[maxn];

bool cmp(Node a,Node b){
    return a.exp>b.exp;
}
int main()
{
    int m,n;
    int flag = 0;
    int exp;
    double coe;

    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>exp>>coe;
        a[i].coe = coe;
        a[i].exp = exp;
    }

    cin>>m;
    for(int i=0; i<m; i++)
    {
        cin>>exp>>coe;
        b[i].coe = coe;
        b[i].exp = exp;
    }

    for(int i=0;i<n;i++)
    for(int j=0;j<m;j++){
        if(a[i].coe && b[j].coe){
            c[flag].exp = a[i].exp+b[j].exp;
            c[flag].coe = a[i].coe*b[j].coe;

            flag++;
        }
    }

    sort(c,c+flag,cmp);

    int cnt = 0;
    int flag1 = 0;;
    for(int i=0;i<flag;i++){
        if(c[i].exp==c[i+1].exp){
            d[cnt].coe =c[i].coe+c[i+1].coe;
            d[cnt].exp = c[i].exp;
            i = i+1;

        }else{
            d[cnt].coe =c[i].coe;
            d[cnt].exp = c[i].exp;

        }

        if(d[cnt].coe!=0)
            cnt++;
    }
    cout<<cnt;
    for(int i=0;i<cnt;i++){
        if(d[i].coe!=0){
           printf(" %d %.1f",d[i].exp,d[i].coe);
        }

    }

    cout<<endl;

    //cout << "Hello world!" << endl;
    return 0;
}

注意只统计非零项的个数

猜你喜欢

转载自blog.csdn.net/jackson_j/article/details/100129177
今日推荐