PAT1002:A+B for Polynomials

Posted 0kk470

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT1002:A+B for Polynomials相关的知识,希望对你有一定的参考价值。

1002. A+B for Polynomials (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

思路

题目要求打印两个多项式相加后的多项式的指数和系数。

用map<指数,系数>这样的关联形式来模拟相加就很简单了,找到对应的指数(键)计算对应的系数(值)就行。
特别注意的情况:指数的系数相加如果为0,那么这个指数和其对应的系数就不用输出了(相消了),而且对应的第一个输出的数字——指数个数也要减1。

代码
#include<iostream>
#include<map>
#include<iomanip>
#include<iterator>
using namespace std;
int main()
{
   int k1,ksum = 0;
   while(cin >> k1)
  {
   map<int,double> sum;  //<指数,系数>
   for(int i = 0;i < k1;i++)
   {
      int n;double a;
      cin >> n >> a;
      sum.insert(pair<int,double>(n,a));
      ksum++;
   }

   int k2;
   cin >> k2;
   for(int i = 0;i < k2;i++)
   {
      int n;double a;
      cin >> n >> a;
      if(sum.count(n) > 0)
      {
        sum[n] += a;
        if(sum[n] == 0)
            ksum--;
      }
      else
      {
         sum.insert(pair<int,double>(n,a));
         ksum++;
      }

   }

   cout << ksum;
   for(map<int,double>::reverse_iterator it = sum.rbegin(); it != sum.rend();it++)
   {
       if(it->second != 0)
       {
         cout << " " << it->first;
         cout <<" "<< fixed << setprecision(1) << it->second;
       }

   }
   cout << endl;
  }
}

 

以上是关于PAT1002:A+B for Polynomials的主要内容,如果未能解决你的问题,请参考以下文章

PAT A1002 A+B for Polynomials

PAT1002 A+B for Polynomials

PAT 甲级 1002 A+B for Polynomials

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

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

每天一道PAT1002 A+B for Polynomials