PAT 1009 Product of Polynomials

#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<cmath>
#include<iomanip>
using namespace std;

struct Node
{
    int exp;
    double coe;
};
vector<Node> vRes;

//将两个多项式相加,最后的结果保存在v1中。
//即将两个有序链表merge在一起。
void addPols(vector<Node> &v1,vector<Node> &v2)
{
    /* 这段代码导致了段错误,因为product函数中会执行v2.clear();
    而v2此时又赋值给了v1,所以v1再访问的时候,就出现了段错误。
    但不是一直断错误,所以vector的clear函数并没有将内容置为空。
    if(v1.size() == 0)
    {
        v1 = v2;
        return;
    }
    */
    vector<Node>::iterator it1 = v1.begin();
    vector<Node>::iterator it2 = v2.begin();
    while(it1!=v1.end() && it2!=v2.end())
    {
        if(it1->exp < it2->exp)
        {
            v1.insert(it1,*it2);
            it2++;
        }
        else if(it1->exp > it2->exp)
            it1++;
        else if(it1->exp == it2->exp)
        {
            it1->coe += it2->coe;
            it1++;
            it2++;
        }
    }
    
    while( it2!=v2.end() )
    {
        v1.push_back(*it2);
        it2++;
    }
}

//两个多项式相乘.
void product(vector<Node> &v1,vector<Node> &v2)
{
    vector<Node> tmpPol;    

    for(vector<Node>::iterator it1=v1.begin(); it1!=v1.end(); it1++)
    {
        tmpPol.clear();//清空tmpPol中的节点。
        for(vector<Node>::iterator it2=v2.begin(); it2!=v2.end(); it2++)
        {
            Node tmpNode;
            tmpNode.exp = it1->exp + it2->exp;
            tmpNode.coe = (it1->coe)*(it2->coe);
            tmpPol.push_back(tmpNode);
        }
        addPols(vRes,tmpPol);
    }
}


//打印结果
void printRes(vector<Node> &v)
{
    vector<Node>::iterator it;
    //原来第一个test case一直过不了的原因是因为精度的问题。
    for (it = v.begin(); it != v.end(); ) {
        if (fabs(it->coe) <= 1e-10) //此时可以认为是0
        {
            it = v.erase(it);
        }
        else
            it++;
    }
    it = v.begin();
    cout<<v.size();
    while(it!=v.end())
    {
        cout<<" "<<it->exp<<" "<<fixed<<setprecision(1)<<it->coe;
        it++;
    }
    cout<<endl;
}

int main()
{
    int k1,k2,i;
    vector<Node> v1,v2;//输入的两个多项式
    cin>>k1;
    for(i=0; i<k1; i++)
    {
        Node tmpNode;
        cin>>tmpNode.exp>>tmpNode.coe;
        v1.push_back(tmpNode);
    }
    cin>>k2;
    for(i=0; i<k2; i++)
    {
        Node tmpNode;
        cin>>tmpNode.exp>>tmpNode.coe;
        v2.push_back(tmpNode);
    }
    product(v1,v2);
    printRes(vRes);
    return 0;
}

 

posted @ 2012-12-01 20:40  Frank@609  Views(794)  Comments(0Edit  收藏  举报