zoukankan      html  css  js  c++  java
  • 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;
      }
    }
  • 相关阅读:
    检查IP地址是否有效(delphi)
    Oracle 常用操作
    DBGrid中顯示行號的終極解決方案(Delphi篇)
    从零开始学Java 第24章 网络聊天室
    JavaScript的循环结构和经典题目
    html5/css3布局(一)
    html常用的基本标签
    HTML5——css基础语法
    JavaScript函数使用和DOM节点
    C语言Ⅰ|博客作业07
  • 原文地址:https://www.cnblogs.com/0kk470/p/7635246.html
Copyright © 2011-2022 走看看