pat1002. A+B for Polynomials (25)

来源:互联网 发布:遇见吧软件 编辑:程序博客网 时间:2024/05/09 00:15

嗯也是个简单题

#include <iostream>#include <algorithm>#include <stack>using namespace std;struct Node{    int coeff=0;    double expon;};int main(){    ios::sync_with_stdio(false);    stack<Node>a;    stack<Node>b;    stack<Node> res;    Node tmp;    int m,n;    cin>>m;    for(int i=0;i<m;i++){        cin>>tmp.coeff>>tmp.expon;        a.push(tmp);    }    cin>>n;    for(int i=0;i<n;i++){        cin>>tmp.coeff>>tmp.expon;        b.push(tmp);    }    Node ta,tb;    while(a.size() && b.size()){        ta = a.top();        tb = b.top();        if(ta.coeff==tb.coeff){            tmp.coeff = ta.coeff;            tmp.expon = ta.expon+tb.expon;            if(tmp.expon) res.push(tmp);            a.pop();            b.pop();        }else{            if(ta.coeff>tb.coeff){                tmp.coeff = tb.coeff;                tmp.expon = tb.expon;                res.push(tmp);                b.pop();            }            if(ta.coeff<tb.coeff){                tmp.coeff = ta.coeff;                tmp.expon = ta.expon;                res.push(tmp);                a.pop();            }        }    }    while(a.size()){        ta = a.top();        tmp.coeff = ta.coeff;        tmp.expon = ta.expon;        a.pop();        res.push(tmp);    }    while(b.size()){        tb = b.top();        tmp.coeff = tb.coeff;        tmp.expon = tb.expon;        res.push(tmp);        b.pop();    }    cout<<res.size();    while(res.size()){        tmp = res.top();        res.pop();    //  cout<<" "<<tmp.coeff<<" "<<tmp.expon;        printf(" %d %.1f",tmp.coeff,tmp.expon);    }    return 0;}

这个题要注意的是答案中指数只可以有一个小数
还有就是要注意当两个数的指数相加为0的时候的处理

原创粉丝点击