PAT_A 1002 A+B for Polynomials
PAT_A 1002 A+B for Polynomials
分析
本题是多项式相加,按指数非递增顺序输入两多项式,对应次数相加即可,需要注意的是一多项式中可能会有多项次数相同的项,不能简单的赋值;还需要注意特殊情况,如多项式相加后消去的情况。
这里找到了某大佬的测试用例如下,可以辩证的参考借鉴。
我的全部测试
test result 2 1 2.4 0 3.2
2 2 1.5 1 0.53 2 1.5 1 2.9 0 3.2 3 2 2.5 1 2.4 0 3.2
2 2 1.5 1 0.53 2 4.0 1 2.9 0 3.2 1 0 3.2
1 0 -3.20 1 0 3.2
1 0 7.891 0 6.1 3 2 2.5 1 2.4 0 3.2
2 2 -2.5 1 0.52 1 2.9 0 3.2 3 2 2.5 2 2.4 0 3.2
2 2 -2.5 1 0.53 2 2.4 1 0.5 0 3.2 10 2 2.5 2 2.4 0 3.2 2 2.5 2 2.4 0 3.2 2 2.5 2 2.4 0 3.2 0 4
10 2 -2.5 1 0.5 2 -2.5 1 0.5 2 -2.5 1 0.5 2.5 2 2.4 0 3.2 0 43 2 10.1 1 1.5 0 20.8
题目的描述
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.
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
AC的代码
#include<bits/stdc++.h>
using namespace std;
int main(){
int K,i=0,c=0;
array<float, 1001> A{0},B{0};
cin>>K;
while(K){
K--;
int t=0;
float t1;
cin>>t>>t1;
A[t]+=t1;
}
cin>>K;
while(K){
K--;
int t=0;
float t1;
cin>>t>>t1;
B[t]+=t1;
}
for(int i=0;i<1001;i++){
A[i]+=B[i];
if(A[i]<=-0.1||A[i]>=0.1)c+=1;
}
cout<<c;
for(int i=1000;i>-1;i--){
if(A[i]<=-0.1||A[i]>=0.1){
printf(" %d %.1f",i,A[i]);
}
}
cout<<endl;
return 0;
}
本文来自博客园,作者:ghosteq,转载请注明原文链接:https://www.cnblogs.com/ghosteq/p/15841216.html