美文网首页PAT甲级
1002 A+B for Polynomials (25 分)

1002 A+B for Polynomials (25 分)

作者: zju_dream | 来源:发表于2019-06-06 09:19 被阅读0次

    A+B for Polynomials (25 分)

    题目描述:
    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 N_1 a_{N1} N_2 a_{N2} ... N_K a_{NK}, where K is the number of nonzero terms in the polynomial, N_i and a_{Ni} (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

    注意点:

    1. coefficients可以是负数
    2. 系数为0不进行输出
    3. 如果size为0,直接输出0
    4. 最后没有空格
    #include<iostream>
    #include<map>
    #include<vector>
    
    using namespace std;
    
    map<int, float> poly1;
    int main() {
        for (int i = 0; i < 2; ++i)
        {
            int n1;
            scanf("%d", &n1);
            for (int i = 0; i < n1; ++i)
            {
                int exp;
                float cof;
                scanf("%d%f", &exp, &cof);
                poly1[exp] += cof;
            }
        }
        vector<pair<int, float> > res;
        for(map<int, float>::reverse_iterator it = poly1.rbegin(); it != poly1.rend(); it++) {
            if(it->second != 0) // 两个系数和为0的得过滤掉
                res.push_back(make_pair(it->first, it->second));
        }
    
        printf("%lu", res.size());
        for (int i = 0; i < res.size(); ++i)
        {
            printf(" %d %.1f", res[i].first, res[i].second);
        }
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:1002 A+B for Polynomials (25 分)

        本文链接:https://www.haomeiwen.com/subject/ovcyxctx.html