pat 1009. Product of Polynomials (25)

本文介绍了一种使用结构体数组实现多项式相乘的方法。通过遍历两个多项式的每一项并计算乘积,将结果存储在一个新的结构体数组中。如果相同指数的项出现,则合并它们的系数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值