【PAT甲级】1002 A+B for Polynomials (25 分)

1002 A+B for Polynomials

题目描述

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

思路

由于只有两行多项式,且多项式最多只有1000项,因此只用定义两个向量,将每一项的系数存在对应的索引位置,然后两个向量相加即可

注意:

说明一下多项式的形式,对于输入

  • K N​1 a​N1 N​2 a​N​2 … NK aNK

这个多项式是:

  • a​N1XN​1+a​N2XN​2+…+a​NKXN​K

在样例中,2 1 2.4 0 3.2表示这个多项式有两项,指数为1的系数为2.4,指数为0的系数为3.2,即:

  • 2.4X1+3.2X0

代码

代码使用两个函数,一个是初始化数据init,另一个是对数据进行处理。

初始化的时候,将第一个多项式的系数存在coefficient[0][i]中,第二个存在coefficient[1][i]中。然后对应每一项系数相加

输出前,先记录非零项的系数,输出的时候不输出系数为0的项目

注意: 要使用double数组来储存系数

#include<stdio.h>

#define MAXK 1001

double coefficients[2][MAXK];//store two lines of exponents and coefficients,index is exponent and value is coefficient
int K;
void init();
void process();

int main()
{
    
    
    init();
    process();
    return 0;
}

void init()
{
    
    
    //initialize coefficients array
    for(int i=0;i<2;i++)
        for(int j=0;j<MAXK;j++)
            coefficients[i][j]=0;
    int temp;
    for(int i=0;i<2;i++)//put the number to two int[]
    {
    
    
        scanf("%d",&K);
        for(int j=0;j<K;j++)
        {
    
    
            scanf("%d",&temp);
            scanf("%lf",&coefficients[i][temp]);
        }
    }
    return;
}

void process()
{
    
    
    int count=0;
    for (int i=0; i<MAXK; i++)
    {
    
    
        coefficients[0][i]+=coefficients[1][i];
        if(coefficients[0][i]!=0)//recording the count of the nonezero terms
            count++;
    }
    printf("%d",count);
    for(int i=MAXK-1;i>=0;i--)
    {
    
    
        if(coefficients[0][i]!=0)
            printf(" %d %.1lf",i,coefficients[0][i]);
    }
    printf("\n");
    return;
}

git仓库:A+B for Polynomials

猜你喜欢

转载自blog.csdn.net/qq_35779286/article/details/95069058