C++ - 进阶 1002

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤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

计算多项式A+B

输入格式:

要求包含一个测试数据,每个测试数据要包含两行,每行包括一个多项式:

K N1 an1 N2 an2....NK ank

K是多项式中非零项的个数,Ni和ani是分别指数和系数。k在【1,10】,NK逐个递减【0,1000】

输出格式:

每一个测试数据,你应该在一行中输出A和B的和,和输入的格式一样,要注意在每一行的最后不要包含空格,请精确到小数点后1位。

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

## 多项式A:  2.4*X^1 +3.2*X^0

## 多项式B:  1.5*X^2 + 0.5 *X^1

A+B = 1.5*X^2 +2.9*X^1 + 3.2

转换为输出为: 3  2 1.5 1 2.9 0 3.2  

Sample Output:

3 2 1.5 1 2.9 0 3.2

计算:

#include<stdio>
#include<map>
using namespace::std;
map<int,double> s;
int main()
{    
    int i1,t1;    
    double t2;    
    for(int z=0;z<2;z++)    
    {        
        scanf("%d",&i1);        
        for(int i=0;i<i1;i++)        
        {            
            scanf("%d%lf",&t1,&t2);            
            if(s.count(t1)==0)                
                s[t1]=t2;            
            else                
                s[t1]+=t2;        
        }    
    }    
    i1=0;    
    for(map<int,double>::const_iterator 
        m_it=s.begin();
        m_it!=s.end();m_it++)    
    {        
        if(m_it->second!=0.0&&m_it->second!=-0.0)            
            i1++;    
    }    
    printf("%d",i1);    
    for(map<int,double>::reverse_iterator m_it=s.rbegin();m_it!=s.rend();m_it++)    
    {        
        if(m_it->second!=0.0&&m_it->second!=-0.0)            
            printf(" %d %.1lf",m_it->first,m_it->second);    
    }    
    printf("\n");    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39241397/article/details/82932821
今日推荐