NOIP2013普及组 T2 表达式求值

来源:互联网 发布:棋牌源码交易 编辑:程序博客网 时间:2024/05/21 19:04

OJ地址:洛谷P1981 CODEVS 3292

 

正常写法是用栈

#include<iostream>#include<algorithm>#include<cmath>#include<stack>#include<cstring>#include<cstdio>using namespace std;char c[20000000];stack<long long>num;//数stack<char>sy;//符号void mth(){//运算    int a,b;    char ch;    b=num.top();    num.pop();    a=num.top();    num.pop();    ch=sy.top();    sy.pop();    switch(ch){        case '+': num.push((a+b)%10000);break;        case '*': num.push((a*b)%10000);break;    }    return;}int cmp(int ch){//优先级判断,没有严谨验证过,初步测试没有问题    if(sy.empty() || sy.top()=='(')return 0;    if(ch=='+' || ch=='-')return 1;    if(ch=='*' && sy.top()=='*')return 1;    return 0;int main(){    gets(c);    int len=strlen(c);    c[len]=')';    sy.push('(');    int i;       if(c[0]<'0'||c[0]>'9'){        num.push(0);    }            for(i=0;i<=len;i++){        if(c[i]=='('){            sy.push('(');            continue;        }        if(c[i]>='0' && c[i]<='9')        {            long long x=0;            while(c[i]>='0' && c[i]<='9'){                x=x*10+c[i]-'0';                i++;            }            i--;            num.push(x);            continue;        }        if(c[i]==')'){            while(sy.top()!='(')mth();            sy.pop();            continue;        }                                while(cmp(c[i]))mth();        sy.push(c[i]);    }    while(!sy.empty())mth();    cout<<num.top()%10000; //    printf("%d ",num.top()%10000);    return 0;}正常写法


简单解法

#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespace std;char last;char c;int x=0;int a=0,b=1;int sum=0;int main(){    int i,j;    bool flag=1;    do{        if(cin>>c);        else{            flag=0;            c='+';//相当于在整个串最后补个+号,以完成全部运算        }        if(c>='0' && c<='9')x=x*10+c-'0';        else{            a=x;            x=0;        }        if(c=='*'){            last=1;            b=(a*b)%10000;        }        if(c=='+'){            if(last){                a=(a*b)%10000;                sum=(sum+a)%10000;                b=1;                last=0;            }            else sum+=a;        }            }while(flag==1);    printf("%d",sum%10000);    return 0;}



0 0
原创粉丝点击