PAT 1009

1009. Product of Polynomials (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

This time, you are supposed to find A*B where A and B are two polynomials.

Input Specification:

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

For each test case you should output the product 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 up to 1 decimal place.

Sample Input
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output
3 3 3.6 2 6.0 1 1.6

解析:多项式的相乘,理解这个直接模拟即可,唯一需要的注意的是系数为0项要去除。

Codes:
/*************************************************************************
    > File Name: 1009.cpp
    > Author: 
    > Mail: 
    > Created Time: 2015年12月09日 星期三 17时27分02秒
 ************************************************************************/

#include<iostream>
#include<map>
#include<cstdio>
using namespace std;

int main(){
    map<int, double> result;
    map<int, double> firstPo;
    map<int, double> secondPo;

    int k1;
    cin>>k1;
    int ex;
    double co;
    while(k1--){
        cin>>ex>>co;
        firstPo[ex] = co;
    }

    int k2;
    cin>>k2;
    int ex2;
    double co2;
    while(k2--){
        cin>>ex2>>co2;
        secondPo[ex2] = co2;
    }

    map<int, double>::iterator it = firstPo.begin();
    while(it != firstPo.end()){
        map<int, double>::iterator it2 = secondPo.begin();
        while(it2 != secondPo.end()){
            int tmp1 = it->first + it2->first;
            double tmp2 = it->second * it2->second;
            if(result.count(tmp1) > 0){
                result[tmp1] += tmp2;
            }
            else{
                result[tmp1] = tmp2;
            }
            ++it2;
        }
        ++it;
    }

    //map<int, double>::iterator it;
    for(it=result.begin(); it!=result.end();){
        if(it->second == 0.0){
            result.erase(it++);
        }
        else{
            it++;
        }
    }
    cout<<result.size();
    map<int, double>::reverse_iterator rit = result.rbegin();
    while(rit != result.rend()){
        //c out<<" "<<rit->first<<" "<<rit->second;
        printf(" %d %.1lf",rit->first,rit->second);
        ++rit;
    }
    return 0;
}

 

 

posted on 2015-12-10 13:02  RookieCoder  阅读(129)  评论(0)    收藏  举报

导航