您的位置:首页 > 其它

PAT甲级练习题A1002. A+B for Polynomials

2016-07-17 20:52 453 查看

题目描述

This time, you are supposed to find A+B where A and B are two polynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.

Output

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

题目解析

第一种我使用两个链表储存两个多项式,编程过程中出现两个问题,一个是输出的格式不对;另外一个是在循环中continue使用的不对,导致错误的跳过了循环体中后面的过程,这个找了一个晚上才发现,一直有两个过不了。

第二种是使用了数组的下标代表次数,因为次数小于1000,所以可以直接用简单的方法。而且只要一个数组就OK了。所以做题目的时候要注意条件,选择合适的简单的方法解决问题。

代码

第一种

//错误的continue
if ( N1==N2 )
{
++i, ++j;
if (an1 + an2 < 0.1)
{
continue;
}
element ele(N1, an1 + an2);
out.push_back(ele);
}


改正后

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;

class element
{
public:
int expo;
double coeff;
element(int ex = 0, double co = 0) :expo(ex), coeff(co) {};
};

int main()
{
int K, N;
double an;
vector<vector<element> > poly(2);
vector<element> out;
for (int i = 0; i < 2; ++i)
{
cin >> K;
for (int j = 0; j < K; ++j)
{
cin >> N >> an;
element ele(N, an);
poly[i].push_back(ele);
}
}
for (int i = 0, j = 0; i < poly[0].size() && j < poly[1].size();)
{
int N1 = poly[0][i].expo, N2 = poly[1][j].expo;
double an1 = poly[0][i].coeff, an2 = poly[1][j].coeff;
//原来的错误在这里
if ( N1==N2 )
{
++i, ++j;
if (an1 + an2 != 0) //这里我觉得可以考虑下浮点数的边界问题,不过通过了
{
element ele(N1, an1 + an2);
out.push_back(ele);
}
}
else if (N1 > N2)
{
element ele(N1, an1);
out.push_back(ele);
++i;
}
else
{
element ele(N2, an2);
out.push_back(ele);
++j;
}

if (i == poly[0].size())
{
for (int k = j; j < poly[1].size(); ++j)
{
out.push_back(poly[1][j]);
}
}
else if (j == poly[1].size())
{
for (int k = i; i < poly[0].size(); ++i)
{
out.push_back(poly[0][i]);
}
}

}
cout << out.size();
for (int i = 0; i < out.size(); ++i)
{
printf(" %d %.1f",out[i].expo,out[i].coeff);
}
cout << endl;
system("pause");
return 0;

}


第二种

#include<iostream>
#include<vector>

using namespace std;
int maxexp = 1001;
vector<double> poly(maxexp, 0);

int main()
{
int K, N;
double an;
int i = 2;
while (i--)
{
cin >> K;
while (K--)
{
cin >> N >> an;
poly
+= an;
}
}
int cnt = 0;
for (int i = maxexp - 1; i >= 0; --i)
{
if (poly[i] != 0)
{
++cnt;
}
}
cout << cnt;
if (cnt != 0)
{
for (int i = maxexp - 1; i >= 0; --i)
{
if (poly[i] != 0)
{
printf(" %d %.1f", i, poly[i]);
}
}
}
cout << endl;
system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: