首页 > 学院 > 开发设计 > 正文

1002. A+B for Polynomials (25)

2019-11-11 05:19:19
字体:
来源:转载
供稿:网友

题目:

This time, you are supposed to find A+B where A and B are two polynomials.

InputEach 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.OutputFor 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 Input2 1 2.4 0 3.22 2 1.5 1 0.5Sample Output3 2 1.5 1 2.9 0 3.2

题目地址:https://www.patest.cn/contests/pat-a-PRactise/1002

解答:

#include<stdio.h>struct PolyNode {  int expo;  double coef;};struct Polynomial {  int Size;  struct PolyNode Array[20];};int main(){  struct Polynomial P1, P2, P;  P.Size = 0;  scanf("%d", &P1.Size);  for (int i = 0; i < P1.Size; i++)    scanf("%d %lf", &P1.Array[i].expo, &P1.Array[i].coef);    scanf("%d", &P2.Size);  for (int i = 0; i < P2.Size; i++)    scanf("%d %lf", &P2.Array[i].expo, &P2.Array[i].coef);  int i = 0, j = 0;  while (i < P1.Size && j < P2.Size) {    if (P1.Array[i].expo > P2.Array[j].expo) {      P.Array[P.Size].coef = P1.Array[i].coef;      P.Array[P.Size].expo= P1.Array[i].expo;      i++;      P.Size++;    }    else if (P1.Array[i].expo < P2.Array[j].expo) {      P.Array[P.Size].coef = P2.Array[j].coef;      P.Array[P.Size].expo = P2.Array[j].expo;      j++;      P.Size++;    }    else {      P.Array[P.Size].expo = P1.Array[i].expo;      P.Array[P.Size].coef = P1.Array[i].coef + P2.Array[j].coef;      i++;      j++;      if (P.Array[P.Size].coef > 10e-6)        P.Size++;    }  }  while (i < P1.Size) {    P.Array[P.Size].coef = P1.Array[i].coef;    P.Array[P.Size].expo = P1.Array[i].expo;    i++;    P.Size++;  }  while (j < P2.Size) {    P.Array[P.Size].coef = P2.Array[j].coef;    P.Array[P.Size].expo = P2.Array[j].expo;    j++;    P.Size++;  }  printf("%d", P.Size);  for (i = 0; i < P.Size; i++) {    printf(" %d %.1f", P.Array[i].expo, P.Array[i].coef);  }  return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表