码迷,mamicode.com
首页 > 其他好文 > 详细

【每天一道PAT】1002 A+B for Polynomials

时间:2020-04-01 13:05:16      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:rate   --   iostream   att   and   image   where   inf   tput   

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();
    }
}


技术图片

【每天一道PAT】1002 A+B for Polynomials

标签:rate   --   iostream   att   and   image   where   inf   tput   

原文地址:https://www.cnblogs.com/xinyuLee404/p/12611673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!