PAT_1002: A+B for Polynomials

来源:互联网 发布:为知笔记怎么分享 编辑:程序博客网 时间:2024/06/08 19:45

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.22 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3
备注:注意结果中系数为0的项不需要输出
#include<stdio.h>struct term{int expo;double coef;};int main(){int k1,k2,i,j,k,r;double temp_coef;struct term Poly1[10],Poly2[10];struct term ResultPoly[2000];scanf("%d",&k1);for(i=0;i<k1;i++){scanf("%d",&Poly1[i].expo);scanf("%lf",&Poly1[i].coef);}scanf("%d",&k2);for(j=0;j<k2;j++){scanf("%d",&Poly2[j].expo);scanf("%lf",&Poly2[j].coef);}k = 0;for(i=0,j=0;i<k1 && j<k2;){if(Poly1[i].expo==Poly2[j].expo){temp_coef = Poly1[i].coef+Poly2[j].coef;if(temp_coef!=0){ResultPoly[k].coef = temp_coef;ResultPoly[k].expo = Poly1[i].expo;i++;j++;k++;}else{i++;j++;}}else if(Poly1[i].expo>Poly2[j].expo){if(Poly1[i].coef!=0){ResultPoly[k].coef = Poly1[i].coef;ResultPoly[k].expo = Poly1[i].expo;i++;k++;}else{i++;}}else{if(Poly2[j].coef!=0){ResultPoly[k].coef = Poly2[j].coef;ResultPoly[k].expo = Poly2[j].expo;j++;k++;}else{j++;}}}/*attach the rest part*/if(i<k1) /*attach Poly1*/{for(;i<k1;i++){if(Poly1[i].coef!=0){ResultPoly[k].coef = Poly1[i].coef;ResultPoly[k].expo = Poly1[i].expo;k++;}}}if(j<k2) /*attach Poly2*/{for(;j<k2;j++){if(Poly2[j].coef!=0){ResultPoly[k].coef = Poly2[j].coef;ResultPoly[k].expo = Poly2[j].expo;k++;}}}printf("%d",k);for(r=0;r<k;r++){printf(" %d %.1lf",ResultPoly[r].expo,ResultPoly[r].coef);}return 0;}

.2
原创粉丝点击