P1175 表达式的转换(栈+模拟)
  • 板块灌水区
  • 楼主Grace34
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/9/11 21:08
  • 上次更新2024/9/11 22:13:35
查看原帖
P1175 表达式的转换(栈+模拟)
927900
Grace34楼主2024/9/11 21:08

悬关求调*3

#include<bits/stdc++.h>
using namespace std;
vector<long long> a;
char st[105],top;
int pr[128];
char ch;
char op[5]={'+','-','*','/','^'};
long long get_op(char c){
    if(c=='+')return 1e10;
    if(c=='-')return 1e10+1;
    if(c=='*')return 1e10+2;
    if(c=='/')return 1e10+3;
    if(c=='^')return 1e10+4;
}
void print(){
    for(int i=0;i<a.size();i++){
        if(a[i]>=1e10)cout<<op[int(a[i]-1e10)]<<" ";
        else cout<<a[i]<<" ";
    }
    cout<<"\n";
}
int power(int a,int b){
    int s=1;
    while(b--)s*=a;
    return s;
}
void calc(){
    int i,tmp;
    for(i=0;i<a.size();i++)
        if(a[i]>=1e10)break;
    if(a[i]==1e10)tmp=a[i-2]+a[i-1];
    else if(a[i]==1e10+1)tmp=a[i-2]-a[i-1];
    else if(a[i]==1e10+2)tmp=a[i-2]*a[i-1];
    else if(a[i]==1e10+3)tmp=a[i-2]/a[i-1];
    else if(a[i]==1e10+4)tmp=pow(a[i-2],a[i-1]);
    a[i-2]=tmp;
    a.erase(a.begin()+i-1,a.begin()+i+1);
    print();
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    pr['+']=1;pr['-']=1;pr['*']=2;pr['/']=2;pr['^']=3;pr['(']=0;
    while((ch=getchar())!=EOF&&ch!='\n'){
        if(ch=='(')st[++top]=ch;
        else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^'){
            while(pr[ch]<=pr[st[top]])a.push_back(get_op(st[top--]));
            st[++top]=ch;
        }
        else if(ch==')'){
            while(st[top]!='(')a.push_back(get_op(st[top--]));
            top--;
        }
        else if(isdigit(ch))a.push_back(ch^48);
    }
    while(top)a.push_back(get_op(st[top--]));
    print();
    while(a.size()>1)calc();
    return 0;
}
2024/9/11 21:08
加载中...