PAT甲级1002. A+B for Polynomials (25)

来源:互联网 发布:淘宝宝贝详情图模板 编辑:程序博客网 时间:2024/06/07 13:21

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

#include <cstdio>using namespace std;#include <vector>struct Polynode{    int expo;    float coeff;    Polynode(int x,float y):expo(x),coeff(y){}}; int main(){    vector<Polynode> Poly1;     vector<Polynode> Poly2;    int k1,k2; //number of nonzero terms in polynomial    int N; //exponent    float A; //coefficient    /*    输入多项式:     多项式的各项已经按指数降序排好序了,所以直接push_back即可    */     scanf("%d",&k1);    for(int i=0;i<k1;i++){        scanf("%d %f",&N,&A);        Poly1.push_back(Polynode(N,A));    }    scanf("%d",&k2);    for(int i=0;i<k2;i++){        scanf("%d %f",&N,&A);        Poly2.push_back(Polynode(N,A));    }    /*     计算2个多项式的和    写法有点像 mergesort的merge函数     */     vector<Polynode> ANS;    int i=0,j=0;    while(i<Poly1.size()&&j<Poly2.size()){        if(Poly1[i].expo>Poly2[j].expo) {            ANS.push_back(Poly1[i]);            i++;        }        else if(Poly1[i].expo<Poly2[j].expo){            ANS.push_back(Poly2[j]);            j++;        }        else{            float sum=Poly1[i].coeff+Poly2[j].coeff;            if(sum!=0) {                ANS.push_back(Polynode(Poly1[i].expo,sum));            }            i++;j++;        }    }    while(i<Poly1.size()) {        ANS.push_back(Poly1[i]);        i++;    }     while(j<Poly2.size()) {        ANS.push_back(Poly2[j]);        j++;    }    /*打印输出    本题没有什么坑点     */     printf("%d",ANS.size());    for(int i=0;i<ANS.size();i++){        printf(" %d %.1f",ANS[i].expo,ANS[i].coeff);    }    return 0;}
0 0
原创粉丝点击