• PAT1002 A+B for Polynomials


    题目描述

    This time, you are supposed to find A+B where A and 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 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 1K10,0NK​​<<N2​​<N1​​1000.

    Output Specification:

    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
    

    题目求解

    这道题不难,除了题目所提示的,还需要注意的是,两个多项式求和以后,系数和为0的项。

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<algorithm>
     4 #include<map>
     5 #include<iomanip>
     6 
     7 using namespace std;
     8 
     9 int m[1002] = {0};
    10 map<int, double> mm;
    11 
    12 int main(){
    13     int k;  //k number of nonzero terms
    14     int n;
    15     double a;   //n is exponents, a is coefficients
    16     cin>>k;
    17     for(int i=0;i<k;i++){
    18         cin>>n>>a;
    19         if(m[n]==0){
    20             m[n] = 1;
    21             m[1001] += 1;
    22             mm[n] = a;
    23         }
    24         else{
    25             mm[n] += a;
    26         }
    27     }
    28     cin>>k;
    29     for(int i=0;i<k;i++){
    30         cin>>n>>a;
    31         if(m[n]==0){
    32             m[n] = 1;
    33             m[1001] += 1;
    34             mm[n] = a;
    35         }
    36         else{
    37             mm[n] += a;
    38         }
    39     }
    40     for(int i=1000;i>=0;i--){
    41         if(m[i]!=0&&mm[i]==0.0){
    42             m[1001]--;
    43         }
    44     }
    45     cout<<m[1001];
    46     for(int i=1000;i>=0;i--){
    47         if(m[i]!=0&&mm[i]!=0.0){
    48             cout<<" "<<i<<" "<<fixed<<setprecision(1)<<mm[i];
    49         }
    50     }
    51     cout<<endl;
    52     return 0;
    53 }
  • 相关阅读:
    循环神经网络
    相似度计算(余弦距离/欧式距离)
    最常见Linux操作
    注意力机制总结
    随机打乱数组算法、蓄水池算法
    6.1 数据结构---树(遍历)
    Node.js调用C/C++
    linux中nmcli命令详解
    stylus入门使用方法
    webpack CommonsChunkPlugin详细教程
  • 原文地址:https://www.cnblogs.com/sgatbl/p/9551367.html
Copyright © 2020-2023  润新知