pat 1009. Product of Polynomials (25)

来源:互联网 发布:淘宝如何设置快递模板 编辑:程序博客网 时间:2024/06/07 16:20
  1. 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 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<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;typedef struct{    double a;    int b;    int next;}node;void init(int &k,node p[]){    scanf("%d",&k);    for (int i=1;i<=k;i++)    {        scanf("%d%lf",&p[i].b,&p[i].a);        p[i-1].next=i;    }}void INSERT(int &k,node p[],double a,int b){    for (int head=0,now=p[0].next;;head=p[head].next,now=p[now].next)    {        if (now==-1){        k++;        p[k].a=a;p[k].b=b;        p[k].next=-1;        p[head].next=k;        break;        }        if (p[now].b==b)        {            p[now].a+=a;            break;        }        if (p[now].b<b)        {            k++;            p[k].a=a;p[k].b=b;            p[k].next=p[head].next;            p[head].next=k;            break;        }       }}int main(){    int i,j,k,t;    int k1,k2,kans=0;    node p1[20],p2[20],pans[1000];    init(k1,p1);    init(k2,p2);    pans[0].next=-1;    for (i=1;i<=k1;i++)        for (j=1;j<=k2;j++)        {            INSERT(kans,pans,p1[i].a*p2[j].a,p1[i].b+p2[j].b);        }    int cnt=0;    for (i=pans[0].next;i!=-1;i=pans[i].next)        if (pans[i].a!=0) cnt++;    printf("%d",cnt);    for (i=pans[0].next;i!=-1;i=pans[i].next)        if (pans[i].a!=0)             printf(" %d %.1f",pans[i].b,pans[i].a);}
原创粉丝点击