hdu 3350 #define is unsafe && hdu3328 Flipper

hdu3350

题意:按照宏定义的规则,计算一个给定的宏定义中‘+’的运算次数。

分析:用栈实现的纯模拟的题目

View Code
#include<iostream>
#include<algorithm>
#include<stack>
#define MAXN 1000+10
using namespace std;
struct number
{
int x,num;
};//保存出现过的数,以及该数字执行‘+’的次数
stack<number> st;//保存出现过的数字
stack<char> oper;//保存操作符
char str[MAXN];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",str);
int len=strlen(str);
number xx,tmp1,tmp2;
for(int i=0;i<len;i++)
{
if(str[i]>='0' && str[i]<='9')//如果是数字,则把整个数 都读出来,压入栈中
{
int a=str[i]-'0';
i++;
while(str[i]>='0' && str[i]<='9')
{
a=a*10+str[i++]-'0';
}
i--;
xx.x=a;xx.num=0;
st.push(xx);
}
else if(str[i]=='+' || str[i]=='(')//直接压入栈中
oper.push(str[i]);
else if(str[i]==',')//如果是‘,’,则把‘,’左边连续的‘+’进行运算, 运算结果重新压入栈中
{
while(!oper.empty() && oper.top()=='+')
{
tmp1=st.top();
st.pop();
tmp2=st.top();
st.pop();
tmp1.x+=tmp2.x;
tmp1.num+=tmp2.num+1;
st.push(tmp1);
oper.pop();
}
}
else if(str[i]==')')//遇到‘)’,则说明有一个MAX 可以执行,但要先把左边连续的‘+’运算完
{
while(!oper.empty() && oper.top()=='+')
{
tmp1=st.top();
st.pop();
tmp2=st.top();
st.pop();
tmp1.x+=tmp2.x;
tmp1.num+=tmp2.num+1;
st.push(tmp1);
oper.pop();
}
oper.pop();
tmp2=st.top();
st.pop();
tmp1=st.top();
st.pop();
if(tmp1.x>tmp2.x)
tmp1.num=tmp1.num*2+tmp2.num;
else {
tmp1.x=tmp2.x;
tmp1.num+=tmp2.num*2;
}
st.push(tmp1);
}
}
while(!oper.empty())//遍历完之后,还可能存在操作符没运算,但只可能是‘+’
{
tmp1=st.top();
st.pop();
tmp2=st.top();
st.pop();
tmp1.x+=tmp2.x;
tmp1.num+=tmp2.num+1;
st.push(tmp1);
oper.pop();
}
printf("%d %d\n",st.top().x,st.top().num);//操作符运算完之后,st里面就只剩一个数字了,同时还保存了‘+’的运算次数
st.pop();
}
return 0;
}

 hdu3328

又一道纯模拟的题目

View Code
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
stack<int> st[201];
int a[201];
char op[2][5]={"up","down"};
int main()
{
int n,m,x,cas=0;
char str[201];
while(scanf("%d",&n)==1 && n)
{
scanf("%s",str);
for(int i=0;i<n;i++)
if(str[i]=='U')
a[i]=0;
else a[i]=1;
int right=n-1,left=0;
for(int i=0;i<n;i++)
st[i].push(i);
scanf("%s",str);
for(int i=0;i<n-1;i++)
{
if(str[i]=='R')
{
while(!st[right].empty())
{
int temp=st[right].top();
a[temp]^=1;
st[right-1].push(temp);
st[right].pop();
}
right--;
}
else {
while(!st[left].empty())
{
int temp=st[left].top();
a[temp]^=1;
st[left+1].push(temp);
st[left].pop();
}
left++;
}
}
int i=0,ans[201];
while(!st[left].empty())
{
ans[i++]=st[left].top();
st[left].pop();
}
printf("Pile %d\n",++cas);
scanf("%d",&m);
while(m--)
{
scanf("%d",&x);
printf("Card %d is a face %s %d.\n",x,op[a[ans[x-1]]],ans[x-1]+1);
}
}
return 0;
}
原文地址:https://www.cnblogs.com/nanke/p/2364573.html