1002 A+B for Polynomials

该博客介绍了如何实现PAT(A+B for Polynomials)题目所要求的多项式求和算法。通过读取输入的多项式数据,将非零项的指数和系数存储到数组中,然后对两个多项式进行逐项求和,将结果存入动态数组,并按要求格式输出。博客提供了C++代码示例,展示了如何处理和输出求和后的多项式。
摘要由CSDN通过智能技术生成

题目来源:PAT (Advanced Level) Practice 1002 A+B for 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 sum 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 to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

思路:

1. 将两个多项式分别保存到两个double类型的数组a和b中去,其中指数部分使用数组的下标,系数部分使用数组元素的值;

2. 使用循环对两个多项式从最高项到最低项求和(相同指数的项的系数相加),并且将相加的结果按照 指数、系数 的顺序储存到动态数组v中;

3. 按照要求输出;先输出和的项数,在从高位到低位依次输出指数和系数;

#include <iostream>  //vxgzh:xtsn
using namespace std;
#include <vector>
#include <iomanip>
#include <cmath>
#define N 1005
double a[N],b[N];   //保存多项式a和b
vector <double> v;

int main()
{
    int k,i,x;
    double y;
    cin>>k;
    for(i=0;i<k;i++)  //输入多项式a
    {
        cin>>x>>y;
        a[x]=y;
    }
    cin>>k;
    for(i=0;i<k;i++) //输入多项式b
    {
        cin>>x>>y;
        b[x]=y;
    }
    for(i=N-1;i>=0;i--)   //对多项式a和b进行求和,从最高项到最低项
    {
        y=a[i]+b[i];
        if(fabs(y)<0.000001)  //判断系数是否为0
            continue;
        else
        {
            v.push_back(i); //将求和的指数放入v中
            v.push_back(y);//将求和的系数放入v中
        }
    }
    cout<<v.size()/2;
    for(i=0;i<v.size();i+=2)  //输出
        cout<<" "<<(int)v[i]<<" "<<fixed<<setprecision(1)<<v[i+1];   
    cout<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值