考试前就停在这题上,和表达式求值很像,当时想用波兰符号法写,考完试后,就用栈来写了,这里运算符只有‘+’,所以不用处理那些优先级,就变的很简单了,读入数字时,当符号栈顶是+,那么就和前一个数运算,当读入到‘,’或‘)’时,如果栈顶还有‘+’那么就进行运算,直到是‘(’,最后就只剩一个数了,和表达式求值基本上是一样的,不过这个简单点。
Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
5232754 | 2012-01-06 16:49:34 | Accepted | 3350 | 0MS | 212K | 1733 B | C++ | xym2010 |
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<stack>
using namespace std;
struct state
{
int tot,num;
}tem,in,out;
stack <struct state> st;
stack < char > cst;
int n,m;
char s[10005];
int main()
{
int t;
scanf("%d",&t);getchar();
while(t--)
{
gets(s);
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(s[i]<='9'&&s[i]>='0')
{
int tep=0;
while(s[i]<='9'&&s[i]>='0')
{
tep=tep*10+s[i]-'0';
i++;
}
if(!cst.empty()&&cst.top()=='+')
{
tem=st.top();st.pop();
tem.num+=tep;tem.tot++;
st.push(tem);cst.pop();
}
else
{
tem.num=tep;tem.tot=0;
st.push(tem);
}
i--;
}
else if(s[i]=='+'||s[i]=='(')
cst.push(s[i]);
else if(s[i]==')'||s[i]==',')
{
while(!cst.empty()&&cst.top()=='+')
{
in=st.top();st.pop();
out=st.top();st.pop();
tem.num=in.num+out.num;
tem.tot=in.tot+out.tot+1;
st.push(tem);cst.pop();
}
if(s[i]==')'&&st.size()>=2)
{
in=st.top();st.pop();
out=st.top();st.pop();
if(out.num>in.num)
{
out.tot=out.tot*2+in.tot;
st.push(out);
}
else
{
in.tot=in.tot*2+out.tot;
st.push(in);
}
cst.pop();
}
}
}
while(!cst.empty())
{
while(!cst.empty()&&cst.top()=='+')
{
in=st.top();st.pop();
out=st.top();st.pop();
tem.num=in.num+out.num;
tem.tot=in.tot+out.tot+1;
st.push(tem);
cst.pop();
}
}
printf("%d %d\n",st.top().num,st.top().tot);
st.pop();
}
return 0;
}