N - 秋实大哥搞算数
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
秋实大哥大学物理挂科了(误),于是在下学期的前两周的某一天要悲剧的补考。为了不给学校的挖掘机大楼做贡献,秋实大哥决定在假期里努力复习。当然,良好的计算能力也是非常必要的,毕竟是涉及计算自己做多少分的题能够通过考试的问题。现在他给自己出了一大堆长长的只有涉及整形四则运算式子,然后埋头计算结果。为了检验自己的计算能力,他请你来帮忙。
Input
第一行一个整数T,表示式子的总数。
接下来每一行有一个长度不超过10^6的表达式,只包含正整数和四则运算符号('+', '-', '*', '/')。
保证输入合法。
Output
对于每一个表达式,输出相应的结果,占一行。
保证运算及结果在long long范围以内。
Sample input and output
Sample Input | Sample Output |
---|---|
2
12+5/4-1
4*5/3 | 12
6 |
首先算完所有的乘除法,在算一遍加减法就完成了。
AC代码:
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;
#define T 1000000+50
char s[T];
ll tmp;
ll st[T],top1=0,top2=0;
char sta[T];
int main()
{
#ifdef zsc
freopen("input.txt","r",stdin);
#endif
int n,m,i,j,k;
scanf("%d",&n);
while(n--)
{
top1=0,top2=0;
scanf("%s",s);
tmp = 0;
for(i=0;s[i];++i){
if(s[i]>='0'&&s[i]<='9')tmp = tmp*10 + s[i]-'0';
else {
st[top1++] = tmp;
tmp = 0;
sta[top2++] = s[i];
}
}
st[top1++] = tmp;
int head = 0;
//首先将全部的乘除法算完
for(i=0;i<top2;++i,head++){
if(sta[i]=='*'){
st[head+1] = st[head]*st[head+1];
st[head] = -1;
sta[i] = '0';
}
else if(sta[i]=='/'){
st[head+1] = st[head]/st[head+1];
st[head] = -1;
sta[i] = '0';
}
}
//之后就是解决加减法
stack<ll> ys;head = 0;
for(i=0;i<top1;++i){
if(st[i]>=0){
ys.push(st[i]);
}
if(ys.size()==2){
while(head<top2)
{
if(sta[head]=='+'){
ll t1 = ys.top();ys.pop();
ll t2 = ys.top();ys.pop();
ys.push(t1+t2);
head++;
break;
}
if(sta[head]=='-'){
ll t1 = ys.top();ys.pop();
ll t2 = ys.top();ys.pop();
ys.push(t2-t1);
head++;
break;
}
head++;
}
}
}
printf("%lld\n",ys.top());
}
return 0;
}