【每天一道PAT】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​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.

思路

主函数结构:

1.读入多项式1
2.读入多项式2
3.多项式相加
4.输出结果

选取数据结构:

队列或者链表,由于数据量较小该处使用队列

#include <stdio.h>
#include <queue>
#include <iostream>
using namespace std;
struct Node{
    int expon;//指数
    float coef;//系数
};
queue<Node> P1,P2,P3;
queue<Node> read_polynomial()
{
    int K,a;
    float c;
    queue<Node> P;
    Node node;
    scanf("%d ",&K);
    while(K--)
    {
        cin>>a>>c;
        node.expon =a;
        node.coef = c;
        P.push(node);
    }
    return P;
}
void attach(int a,float c)
{
    Node node;
    if(c == 0) return;//如果系数为0,不入队列
    node.expon = a;
    node.coef = c;
    P3.push(node);
}
void add_polynomials()
{
    while((!P1.empty())&&(!P2.empty()))
    {
        if(P1.front().expon == P2.front().expon)
        {
            attach(P1.front().expon,P1.front().coef+P2.front().coef);
            P1.pop();
            P2.pop();
        }
        else if(P1.front().expon > P2.front().expon)
        {
            attach(P1.front().expon,P1.front().coef);
            P1.pop();
        }
        else
        {
            attach(P2.front().expon,P2.front().coef);
            P2.pop();
        }

    }
    while(!P1.empty())
    {
        P3.push(P1.front());
        P1.pop();
    }
    while(!P2.empty())
    {
        P3.push(P2.front());
        P2.pop();
    }
}

int main()
{

    P1 = read_polynomial();
    P2 = read_polynomial();
    add_polynomials();
    printf("%d",P3.size());
    while(!P3.empty())
    {
        printf(" %d %.1f",P3.front().expon,P3.front().coef);
        P3.pop();
    }
}


解法二

#include <cstdio>
#include <math.h>
#define maxNum  1001
#define err 1E-6
float A[maxNum]= {0};
int U[maxNum] = {0};
using namespace std;
int main()
{
    int k,k_result= 0,a;
    float n;
    for(int i = 0;i<2;i++)
    {
        scanf("%d",&k);
        for(int j = 0;j<k;j++)
        {
            scanf("%d %f",&a,&n);
            A[a]+=n;
            if(U[a]==0) U[a]=1,++k_result;
			if(fabs(A[a])<1E-6) U[a]=0,--k_result;
        }
    }
    printf("%d",k_result);
    for(int i = maxNum;i>=0;i--)
    {
        if(U[i]==1)printf(" %d %.1f",i,A[i]);
    }
    return 0;
}

posted @ 2020-04-01 12:20  XinyuLee  阅读(113)  评论(0编辑  收藏  举报