hdoj1082(栈)

#include<stdio.h>
#include<string.h>
int a[26][2];
int zhan[1000][2];
int top,sum;
int jin(int x)
{
 zhan[top][0]=a[x][0];
 zhan[top][1]=a[x][1];
 top++;
 return 0;
}
int chu()
{
 if(zhan[top-2][1]!=zhan[top-1][0])return 1;
 sum+=zhan[top-1][0]*zhan[top-1][1]*zhan[top-2][0];
 zhan[top-2][1]=zhan[top-1][1];//关键把两个栈合并成一个
 top--;//栈数减少一个
 return 0;
}
int main()
{
 //freopen("input.txt","r",stdin);
 int n,i,x,y,len,p;
 char str[1001];
 char ch;
 scanf("%d",&n);
 getchar();
 for(i=0;i<n;i++)
 {
  scanf("%c%d%d",&ch,&x,&y);
  a[ch-'A'][0]=x;
  a[ch-'A'][1]=y;
  getchar();
 }
 getchar();
 while(gets(str))
 {
  p=0;
  top=0,sum=0;
  len=strlen(str);
  if(len==1)//只有一个输出0
  {
   printf("0\n");
   continue;
  }
  for(i=0;i<len&&!p;i++)
  {
   if(str[i]=='(')continue;//(不做处理
   if(str[i]==')')p=chu();//)出栈
   else jin(str[i]-'A');
  }
  if(p)
   printf("error\n");
  else
   printf("%d\n",sum);
 }
 return 0;
}

 

 

 

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
using namespace std;
const int maxn=30;
typedef struct
{
 int row;
 int col;
}Matrix;
Matrix m[30];
int n;
char stra[10*maxn];
int Solve()
{
 stack<char> par;
 stack<Matrix> ms;
 int len=strlen(stra);
 Matrix m1,m2,m3;
 int ans=0;
 for(int i=0;i<len;i++)
 {
  if(stra[i]==')')
  {
   m2=ms.top();
   ms.pop();
   m1=ms.top();
   ms.pop();
   if(m1.col!=m2.row)
    return -1;
   else
   {
    ans+=(m1.row*m1.col*m2.col);
    m3.row=m1.row; m3.col=m2.col;
    ms.push(m3);
   }
  
  else if(stra[i]=='(')
   continue;
  else
   ms.push(m[stra[i]-'A']);
 }
 return ans;
}
int main(void)
{
 //freopen("f:\\file\\data.txt","r",stdin);
 scanf("%d",&n);
 while(n--)
 {
  char ch;
  int row,col;
  scanf("\n%c%d%d",&ch,&row,&col);
  m[ch-'A'].row=row;
  m[ch-'A'].col=col;
 }
 while(scanf("%s",stra)==1)
 {
  int  ans=Solve();
  if(ans<0)
   printf("error\n");
  else
   printf("%d\n",ans);
 }
 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值