NOIP2013普及组 T2 表达式求值

8 篇文章 0 订阅
3 篇文章 0 订阅

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值