zoukankan      html  css  js  c++  java
  • PAT 1002 A+B for Polynomials(map模拟)

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

    题目意思:两个多项式的相加,每一行第一个数k表示非零系数的个数,之后是每个非零系数的指数和系数。

    解题思路:可以直接使用数组来模拟,这里我使用map复习一下map的用法。

    https://www.cnblogs.com/wkfvawl/p/9387566.html

    #include<iostream>
    #include<algorithm>
    #include<string>
    #include<cstdio>
    #include<map>
    using namespace std;
    int main()
    {
        int T=2;
        int n,k,i;
        double m;
        int cnt=0;
        map<int,double>mp;
        map<int,double>::iterator it;//迭代器
        map<int,double>::reverse_iterator rit;//反向迭代器
        while(T--)
        {
            scanf("%d",&k);
            for(i=0; i<k; i++)
            {
                scanf("%d%lf",&n,&m);//n为指数,m为系数
                mp[n]+=m;
            }
        }
        for(it=mp.begin();it!=mp.end();it++)//系数为0的
        {
            if(it->second!=0)
            {
                cnt++;
                //printf("%lf
    ",it->second);
            }
        }
        printf("%d",cnt);
        //map默认从小到大,可以用逆向迭代器逆序输出
        for(rit=mp.rbegin();rit!=mp.rend();rit++)//系数为0的
        {
            if(rit->second!=0)
            {
                printf(" %d %.1f",rit->first,rit->second);
            }
        }
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    js,js中使用正则表达式
    web开发中文件下载
    EL表达式
    Servlet Filter
    压缩文件 乱码问题(转载)
    MFC CopyDirectory
    SaveFileDialog
    Create Window
    CDateTimeCtrl 设置时间
    键值表
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/11017906.html
Copyright © 2011-2022 走看看