[PAT甲级] 1002 A+B for Polynomials (25分)

最后更新于 2021-01-24 2076 次阅读


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 CODE:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#include<cstring>
#include<iomanip>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
#define MAXN 250005
#define MAXSIZE 10
#define DLEN 4
#define mod 1000000007
const int MOD = 1e9+7;
double a[1005],b[1005],c[1005];
int main(){
    int k;
    scanf("%d",&k);//输入第一行
    while(k--){
        int n;
        double an;
        scanf("%d%lf",&n,&an);
        a[n]=an;//存储到数组,下标为次数,值为系数
    }
    scanf("%d",&k);//输入第二行
    while(k--){
        int n;
        double an;
        scanf("%d%lf",&n,&an);
        b[n]=an;
    }
    k=0;
    for(int i=1005;i>=0;i--){
        c[i]=a[i]+b[i];
        if(c[i]!=0)k++;//合并(这里把b[i]加到a[i]会发生未知的错误,另开一个c[i]就ac了 迷)
    }
    printf("%d",k);
    for(int i=1005;i>=0;i--){
        if(c[i]!=0){
            printf(" %d %.1f",i,c[i]);//保留一位小数
        }
    }

    return 0;
}

此作者没有提供个人介绍
最后更新于 2021-01-24