把栈当成一种存储方式,元素先进后出,适应于对最新的元素操作
如:hdu 1237
#include<cstdio>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int main()
{
char str[210],ct;
int N,len,i,j;
bool f,flag;
double num,t,temp;
while(gets(str)&&strcmp(str,"0")!=0)
{
stack<double>s1;
len=strlen(str);
i=0;
while(i<len)
{
t=0;f=0;
while(str[i]>='0'&&str[i]<='9')
{
t=str[i]-'0'+t*10;
++i;
f=1;
}
if(f)
s1.push(t);
if(i>0)
i++;
if(str[i]=='+'||str[i]=='-')
{
flag=0;
if(str[i]=='-')
flag=1;
i+=2;///
t=0;
while(str[i]>='0'&&str[i]<='9')
{
t=str[i]-'0'+t*10;
++i;
}
if(flag)
t=-t;
s1.push(t);
}
else if(str[i]=='*')
{
i+=2;///
t=0;
while(str[i]>='0'&&str[i]<='9')
{
t=str[i]-'0'+t*10;//
++i;
}
temp=s1.top();
s1.pop();
t*=temp;
s1.push(t);
}
else if(str[i]=='/')
{
i+=2;///
t=0;
while(str[i]>='0'&&str[i]<='9')
{
t=str[i]-'0'+t*10;//'='
++i;
}
temp=s1.top();
s1.pop();
t=temp/t;
s1.push(t);
}
}
num=0;
while(!s1.empty())
{
num+=s1.top();
s1.pop();
}
printf("%.2lf\n",num);
}
return 0;
}
nyoj 305
#include<cstdio>
#include<cstring>
#include<stack>
#include<iostream>
using namespace std;
int main()
{
int N,n,i,len,t1,t2,t;
char a[310];
scanf("%d",&N);
while(N--)
{
stack<int>s1,snum2;
scanf("%s",a);
len=strlen(a);
i=0;
while(i<len)
{
if(islower(a[i]))
{
if(a[i+1]=='d')
s1.push(3);//add()
else if(a[i+1]=='a')
s1.push(2);//max
else
s1.push(1);//min
i+=4;
}
else if(a[i]>='0'&&a[i]<='9')
{
t1=0;
while(a[i]>='0'&&a[i]<='9')//
{
t1=a[i]-'0'+t1*10;
i++;
}
snum2.push(t1);
}
else if(a[i]==')')
{
i++;
t1=snum2.top();
snum2.pop();
t2=snum2.top();
snum2.pop();
t=s1.top();
s1.pop();
if(t==1)
{n=t1<t2?t1:t2;snum2.push(n);}
else if(t==2)
{n=t1>t2?t1:t2;snum2.push(n);}
else
{n=t1+t2;snum2.push(n);}
}
else
i++;
}
cout<<snum2.top()<<endl;
}
return 0;
}