1. 程式人生 > >PAT甲級1002

PAT甲級1002

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;
}