您的位置:首页 > 产品设计 > UI/UE

2016 UESTC Training for Data Structures N - 秋实大哥搞算数 用栈处理表达式

2016-05-01 00:03 531 查看


N - 秋实大哥搞算数


Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)


Submit
Status

秋实大哥大学物理挂科了(误),于是在下学期的前两周的某一天要悲剧的补考。为了不给学校的挖掘机大楼做贡献,秋实大哥决定在假期里努力
复习。当然,良好的计算能力也是非常必要的,毕竟是涉及计算自己做多少分的题能够通过考试的问题。现在他给自己出了一大堆长长的只有涉及
整形四则运算式子,然后埋头计算结果。为了检验自己的计算能力,他请你来帮忙。


Input

第一行一个整数T,表示式子的总数。
接下来每一行有一个长度不超过10^6的表达式,只包含正整数和四则运算符号('+', '-', '*', '/')。
保证输入合法。


Output

对于每一个表达式,输出相应的结果,占一行。
保证运算及结果在long long范围以内。


Sample input and output

Sample InputSample Output
2
12+5/4-1
4*5/3

12
6


Source

2016 UESTC Training for Data Structures Problem N


My Solution

用栈处理表达式

直接STL里的stack

先讨论第一个字符是不是'-'

如果是则记录符号

如果不是则第一个数入栈

然后每次如果+val则直接入栈

如果-val则把-val入栈

如果*或/ 则pop()出栈顶了计算表达式,把结果入栈

处理完后把栈里的东西加起来就好了,直到栈为空

复杂度 O(n);

#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
#include <cstring>
#include <cctype>
#include <cmath>
using namespace std;
typedef long long LL;
const int maxn = 1e6 + 8;

stack<LL> sta;
char line[maxn];

int main()
{
#ifdef LOCAL
freopen("a.txt", "r", stdin);
#endif // LOCAL
int T;
LL ans, val;
scanf("%d", &T);
while(T--){
string str;
char op = '+';
scanf("%s", line);
ans = 0;
int len = strlen(line), sz;
if(isalnum(line[0])) str = line[0];
else op = '-';
for(int i = 1; i < len; i++){
if(isalnum(line[i])) str += line[i];
else {
sz = str.size();
val = 0; //initialize should be put in the front, unless the first one will be wrong
for(int j = 0; j < sz; j++){
val += (str[j]-'0')*pow(10, sz - j - 1);//cout<<pow(10, (sz - j - 1))<<endl;
}
//cout<<str<<endl;
if(op == '+')sta.push(val);
else if(op == '-') sta.push(-val);
else if(op == '*') {LL preval = sta.top();sta.pop();sta.push(preval*val);}
else if(op == '/') {LL preval = sta.top();sta.pop();sta.push(preval/val);}
val = 0;
op = line[i];
str.clear();
//cout<<sta.top()<<endl;
}
}
// to progress the last val which has not been add to val and push into stack
sz = str.size();
for(int j = 0; j < sz; j++){
val += (str[j]-'0')*pow(10, sz - j - 1);
}
if(op == '+')sta.push(val);
else if(op == '-') sta.push(-val);
else if(op == '*') {LL preval = sta.top();sta.pop();sta.push(preval*val);}
else if(op == '/') {LL preval = sta.top();sta.pop();sta.push(preval/val);}

ans = sta.top();sta.pop();
while(!sta.empty()){
ans += sta.top();
sta.pop();
}
printf("%lld\n", ans);
}
return 0;
}


Thank you!

------from ProLights
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: