uva 327

这题就是让算一个表达式的值,要处理变量的自加自减,刚在数据结构课上听了怎么把中序表达弄成后序表达,就趁此试了试,所以过程麻烦了点。

#include <iostream>
#include<cstdio>
#include<algorithm>
#define hp '!'
#define hm '@'
#define tp '#'
#define tm '$'
using namespace std;
char orgn_str[200];
char inodr_str[200];
char postodr_str[200];
int var[200];
int opera_class[200];
void init(void);
char convert(char c,int f);
int main()
{
    init();
    while(gets(orgn_str)!=NULL){
        int i=0,j=0; char c;
        while((c=orgn_str[i++])!=0)
            if(c!=' ') inodr_str[j++]=c;
        inodr_str[j]=0;
        for(int i='a';i<='z';i++) var[i]=i-'a'+1;
        char sta[200]; int top=0; sta[0]=0;
        int varflag=0;
        i=j=0;
        while((c=inodr_str[i])!=0){
            if(c>='a'&&c<='z'){
                postodr_str[j++]=c;
                varflag=1;
            }
            else{
                if(c!=inodr_str[i+1]) varflag=0;
                else{
                    c=convert(c,varflag); i++;
                }
                while(opera_class[sta[top]]>=opera_class[c])
                    postodr_str[j++]=sta[top--];
                sta[++top]=c;
            }
            i++;
        }
        while(top) postodr_str[j++]=sta[top--];
        postodr_str[j]=0; i=j=0;
        int sta2[100]; top=-1;
        char que[100]; int h=0,r=-1;
        while((c=postodr_str[i])!=0){
            if(c>='a'&&c<='z'){
                sta2[++top]=var[c];
                que[++r]=c;
            }
            else{
                if(c=='+') sta2[top-1]=sta2[top-1]+sta2[top],top--;
                if(c=='-') sta2[top-1]=sta2[top-1]-sta2[top],top--;
                if(c==hp)  sta2[top]++,var[que[r]]++;
                if(c==hm)  sta2[top]--,var[que[r]]--;
                if(c==tp)  var[que[r]]++;
                if(c==tm)  var[que[r]]--;
            }
            i++;
        }
        sort(que,que+r+1);
        cout<<"Expression: "<<orgn_str<<endl;
        printf("    value = %d\n",sta2[0]);
        for(;h<=r;h++) printf("    %c = %d\n",que[h],var[que[h]]);
    }
    return 0;
}
void init(){
    opera_class[0]=0;
    opera_class['+']=1; opera_class['-']=1;
    opera_class[hp]=2; opera_class[hm]=2;
    opera_class[tp]=2; opera_class[tm]=2;
}
char convert(char c,int f){
    if(c=='+'){
        if(f) return tp;
        return hp;
    }
    if(f) return tm;
    return hm;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值