1002. A+B for Polynomials (25)

題目描述:
This time, you are supposed to find A+B where A and B are two polynomials.ios

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.spa

Outputcode

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.orm

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.2ci

題目大意:給出兩個多項式,計算這兩個多項式的和並輸出。注意多項式相加規則,係數相同的一項指數相加。
題目思路:此題可以使用hash思想,將指數做爲地址,係數做爲存放內容。(注意數組數據類型是double。)
參考代碼:input

#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1010;
double p[MAXN] = { 0.0 };
int main()
{
  int n;
  memset(p, 0, sizeof(p));
  for (int i = 0; i < 2; i++)
  {
    cin >> n;
    for (int j = 0; j < n; j++)
    {
      int a;
      
      double b;
      cin >> a >> b;
      if (p[a] == 0.0) p[a] = b;
      else
      {
        p[a] += b;
      }
    }
  }
  int cnt =0;
  for (int i = 0; i < MAXN; i++)
  {
    if (p[i] != 0.0) cnt++;
  }
  cout << cnt;
  for (int i = MAXN; i >= 0; i--)
  {
    if (p[i] != 0.0) {
      printf(" %d %.1f", i, p[i]);
    }
  }
  cout << endl;
  return 0;
}
相關文章
相關標籤/搜索