标签:rate -- iostream att and image where inf tput
This time, you are supposed to find A+B where A and B are two polynomials.
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.
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