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;
    }
  • 相关阅读:
    ajax相关知识总结
    http协议
    sass基础常用指南
    自定义上传图片样式并实现上传立即展示该图片
    HTML5 History 模式
    网页打印样式CSS
    session和cookie相关知识总结
    第二个冲刺周期
    软件工程学习进度表(第十三周)
    软件工程学习进度表(第十二周)
  • 原文地址:https://www.cnblogs.com/wkfvawl/p/11017906.html
Copyright © 2011-2022 走看看