PAT甲级1002

PAT甲级1002是一个多项式相加的问题。本人使用map数据结构来保存多项式其中一项,一个键值对中,键对应指数,值对应系数。

多次提交一直报错,后发现主要是输出精度的问题。系数必须保留到小数点后一位。


以下为原题:

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

以下为本人解法源代码:

#include <iostream>
#include<string>
#include<vector>
#include<map>
#include<iomanip>
using namespace std;

int main()
{
    vector<float> A,B;
    float a,b;
    while(cin>>a)
    {
        A.push_back(a);
        if(getchar()=='\n')
            break;
    }
    while(cin>>b)
    {
        B.push_back(b);
        if(getchar()=='\n')
            break;
    }
    map<float,float> pol;
    int a_size=A.size();//第一行输入
    int b_size=B.size();//第二行输入
    for(int i=1;i<a_size-1;i+=2)
        pol.insert(pair<float,float>(A[i],A[i+1]));//将第一行输入存入map,map会自动按照key的升序进行存储
    map<float,float>::iterator iter;
    //将第二行输入存入map
    for(int i=1;i<b_size-1;i+=2)
    {
        iter=pol.find(B[i]);
        if(iter!=pol.end())//指数相同则将系数相加
            pol[B[i]]=pol[B[i]]+B[i+1];
        else//指数不同则将新的式子加入map
            pol.insert(pair<float,float>(B[i],B[i+1]));
    }
    //遍历删除系数为0的式子
    for(iter = pol.begin(); iter != pol.end();)
    {
        if(iter->second==0)
        {
            iter=pol.erase(iter);
        }
        else
            iter++;
    }
    //map大小不为0
    if(pol.size()!=0)
    {
        cout<<pol.size()<<" ";
        map<float,float>::iterator riter=pol.end();
        riter--;
        while(riter!=pol.begin())
        {
            cout<<fixed<<setprecision(0)<<riter->first<<" ";
            cout<<fixed<<setprecision(1)<<riter->second<<" ";
            riter--;
        }
        cout<<fixed<<setprecision(0)<<riter->first<<" ";
        cout<<fixed<<setprecision(1)<<riter->second;
    }
    else
        cout<<pol.size();
    return 0;
}

控制精度时如直接这样写:

 cout<<riter->first<<" "<<fixed<<setprecision(1)<<riter->second<<" ";

则会将指数的精度也变为小数点后一位,例如


而希望的输出是这样:


所以源代码中专门也控制了指数的精度:

cout<<fixed<<setprecision(0)<<riter->first<<" ";

至于为什么会这样我没有深究,还有这样的解决方案肯定不是最优的,复杂度略高。


欢迎讨论。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值