1002. A+B for Polynomials (25)
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 Input2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output
3 2 1.5 1 2.9 0 3.2
/*
http://pat.zju.edu.cn/contests/pat-a-practise/1002 1002. A+B for Polynomials (25)
*/
#include<iostream>
#include<string.h>
#include<iomanip>
#include<vector>
using namespace std;
struct term
{
int exponent;//指数
double coefficient;//系数
};
int main()
{
int K1,K2;
vector<term> v1,v2,v3;//分别存输入项,结果项
cin >> K1;
while(K1--)
{
term temp; //临时保存一项
cin>>temp.exponent>>temp.coefficient;
v1.push_back(temp);
//K1--;
}
cin >> K2;
while(K2--)
{
term temp; //临时保存一项
cin>>temp.exponent>>temp.coefficient;
v2.push_back(temp);
//K2--;
}
int total1 = v1.size();
int total2 = v2.size();
int p1 = 0,p2 = 0;
while(p1<v1.size() && p2<v2.size())
{
term temp1 = v1[p1];
term temp2 = v2[p2];
term temp3;
if(temp1.exponent == temp2.exponent)//指数项相等
{
temp3.exponent = temp1.exponent;
temp3.coefficient = temp1.coefficient + temp2.coefficient;
if(temp3.coefficient!=0)
{
v3.push_back(temp3);
}
p1++;
p2++;
}
else if(temp1.exponent> temp2.exponent)
{
if(temp1.coefficient!=0)
{
v3.push_back(temp1);
}
p1++;
}
else
{
if(temp2.coefficient!=0)
{
v3.push_back(temp2);
}
p2++;
}
}
while(p1<v1.size())
{
if(v1[p1].coefficient!=0)
{
v3.push_back(v1[p1]);
}
p1++;
}
while(p2<v2.size())
{
if(v1[p2].coefficient!=0)
{
v3.push_back(v2[p2++]);
}
p2++;
}
//输出
cout<<v3.size();
for(int i =0;i<v3.size();i++)
{
cout<<fixed<<setprecision(1);
cout<<" "<<v3[i].exponent<<" "<<v3[i].coefficient;
}
system("pause");
return 0;
}
在几番尝试未果之后,决定换一种方式,由于题目给出的指数范围至多为1000,座椅这里可以采用大数组的形式保存结果,数组下标即对应着指数值,操作起来方便很多,最后注意调整输出格式,设置setprecision(1),就完美通过,而如果不设置这一句,就会出错,可能测试点上有输入不止一位小数的测试用例吧。另外还有一个要注意的点就是两项相加后系数为0,就不要计入结果中了。一下为参考代码,可通过。
http://pat.zju.edu.cn/contests/pat-a-practise/1002 1002. A+B for Polynomials (25)
*/
#include<iostream>
#include<string.h>
#include<iomanip>
#include<vector>
using namespace std;
int main()
{
double coe[1001];
int k;
int exponent;
double coefficient;
memset(coe,0,sizeof(coe));
cin>> k;
while(k--)
{
cin>>exponent>> coefficient;
coe[exponent] += coefficient;
}
cin>>k;
while(k--)
{
cin>>exponent>> coefficient;
coe[exponent] += coefficient;
}
int count = 0;
for(int i = 0;i<1001;i++)
{
if(coe[i]!=0)
count++;
}
cout<<count;
for(int i =1000 ;i>=0;i--)
{
if(coe[i]!=0)
{
cout<<fixed<<setprecision(1);
cout<<" "<<i<<" "<<coe[i];
}
}
system("pause");
return 0;
}