hdu 3350

考试前就停在这题上,和表达式求值很像,当时想用波兰符号法写,考完试后,就用栈来写了,这里运算符只有‘+’,所以不用处理那些优先级,就变的很简单了,读入数字时,当符号栈顶是+,那么就和前一个数运算,当读入到‘,’或‘)’时,如果栈顶还有‘+’那么就进行运算,直到是‘(’,最后就只剩一个数了,和表达式求值基本上是一样的,不过这个简单点。

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
52327542012-01-06 16:49:34Accepted33500MS212K1733 BC++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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值