60超时
查看原帖
60超时
517637
瀛洲仙子楼主2023/11/24 23:23

rt,创建表达式树的解法超时了求助

#include<bits/stdc++.h>
using namespace std;
map<char,int>prio;
string suff(string in)
{
    prio['+']=prio['-']=1;
    prio['*']=prio['/']=2;
    stack<char>st;
    string ret="";
    for(int i=0;i<in.length();++i)
    {
        if(isdigit(in[i]))ret+=in[i];
        else if(in[i]=='(')st.push('(');
        else if(in[i]==')')
        {
            while(st.top()!='(')
            {
                ret+=st.top();
                st.pop();
            }
            st.pop();
        }
        else
        {
            if(in[i]=='^')st.push('^');
            else
            {
                while(st.size()and prio[st.top()]>=prio[in[i]])
                    {ret+=st.top();st.pop();}
                st.push(in[i]);
            }
        }
    }
    while(st.size())
    {
        ret+=st.top();
        st.pop();
    }
    return ret;
}
struct var
{
    int op;
    char tx;
    int lc,rc;
    var(){tx=0;}
    var(int o,int l,int r,char c)
    {op=o;lc=l;rc=r;tx=c;}
};var tree[105];int cnt;
int build(string post)
{
    stack<int>son;
    for(int i=0;i<post.length();++i)
    {
        if(isdigit(post[i]))
        {
            tree[++cnt]=var(post[i]-48,0,0,0);
            son.push(cnt);
        }
        else
        {
            int rch=son.top();son.pop();
            int lch=son.top();son.pop();
            tree[++cnt]=var(0,lch,rch,post[i]);
            son.push(cnt);
        }
    }
    return son.top();
}
void post(int bt)
{
    if(!bt)return;
    post(tree[bt].lc);
    post(tree[bt].rc);
    if(tree[bt].op)
        cout<<tree[bt].op;
    else cout<<tree[bt].tx;
    cout<<' ';
}
bool flag;
int change(int bt)
{
    if(flag)return 0;
    if(!bt)return 0;
    if(tree[bt].op)
        return tree[bt].op;
    int chlc=change(tree[bt].lc);
    int chrc=change(tree[bt].rc);
    if(!flag)
    {
        if(tree[bt].tx=='+')
            tree[bt].op=chlc+chrc;
        if(tree[bt].tx=='-')
            tree[bt].op=chlc-chrc;
        if(tree[bt].tx=='*')
            tree[bt].op=chlc*chrc;
        if(tree[bt].tx=='/')
            tree[bt].op=chlc/chrc;
        if(tree[bt].tx=='^')
            tree[bt].op=pow(chlc,chrc);
        tree[bt].tx=0;flag=true;
        tree[bt].lc=tree[bt].rc=0;
    }
    return tree[bt].op;
}
int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    string expr;cin>>expr;
    string suf=suff(expr);
    int root=build(suf);
    while(!tree[root].op)
    {
        post(root);
        flag=false;
        change(root);
        cout<<endl;
    }
    cout<<tree[root].op;
    return 0;
}
2023/11/24 23:23
加载中...