PAT(Advanced Level) Practice 1002 A+B for Polynomials(25점)

20617 단어 제목 코드

1002 A+B for Polynomials(25점)


This time, you are supposed to find A + B A+B A+B where A A A and B B 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 a 2 a N 2 . . . N K a N K K N_1 a_{N_1} a_2 a_{N_2} ... N_K a_{N_K} KN1​aN1​​a2​aN2​​...NK​aNK​​ where K K K is the number of nonzero terms in the polynomial, N i N_i Ni​and a N i ( i = 1 , 2 , ⋯ , K ) a_{N_i}(i=1,2,⋯,K) aNi​​(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. 1≤K≤10,0≤N_K<⋯

Output Specification:


For each test case you should output the sum of A A A and B B 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

My code
#include 
#include 

void printarray(double *a, int n)
{
    for (int i = 0; i < n; i++){
        printf("%.1f ", a[i]);
    }
    printf("
"
); } int main(void) { double a[21], b[21]; scanf("%lf", &a[0]); for (int i=1; i <=2*a[0]; i++){ scanf("%lf", &a[i]); } scanf("%lf", &b[0]); for (int i=1; i <=2*b[0]; i++){ scanf("%lf", &b[i]); } int ina, inb; ina = inb = 1; double c[50]; int inc = 1; c[0] = a[0]+b[0]; int s=0; while (ina <= 2*a[0] && inb <= 2*b[0]){ if (a[ina]>b[inb]){ c[inc] = a[ina]; c[inc+1] = a[ina+1]; ina = ina+2; inc = inc+2; s++; } else if (a[ina]<b[inb]){ c[inc] = b[inb]; c[inc+1] = b[inb+1]; inb = inb+2; inc = inc+2; s++; } else{ if ((a[ina+1] + b[inb+1])!=0){ c[inc] = a[ina]; c[inc+1] = a[ina+1] + b[inb+1]; inc = inc+2; ina = ina+2; inb = inb+2; s++; } else{ ina = ina+2; inb = inb+2; } } } while (ina <= 2*a[0]){ c[inc] = a[ina]; c[inc+1] = a[ina+1]; ina = ina+2; inc = inc+2; s++; } while (inb <= 2*b[0]){ c[inc] = b[inb]; c[inc+1] = b[inb+1]; inb = inb+2; inc = inc+2; s++; } if(s==0){ printf("0"); return 0; } printf("%d ", s); for (int i=1; i < inc; i++){ if (i%2==0){ printf("%.1f", c[i]); } else printf("%.0f", c[i]); if (i<inc-1) printf(" "); } return 0; }

좋은 웹페이지 즐겨찾기