POJ 2246 模拟

题意:给定A-Z若干的矩阵,以及一些表达式,根据表达式求出所有矩阵相乘的次数,若中间出现不符合要求的情况,则输出“error”

解法:用栈进行模拟,代码写的奇丑无比。

#include<stdio.h>
#include<string.h>
#include<stack>
#define MAXN 100000
using namespace std;
struct node
{
    int x,y;
}p[300];
char s[MAXN],ch;
int main()
{
    int n,i,j,k,sum;
    bool error;
    scanf("%d",&n);
    getchar();
    for(i=0; i<n; i++)  //读入n个矩阵,并按照顺序存储
    {
        scanf("%c",&ch);
        scanf("%d %d",&p[ch-'A'].x,&p[ch-'A'].y);
        getchar();
    }
    while(gets(s)!=NULL)
    {
        n=26;
        sum=0;
        error=false;
        stack<int>sta;
        for(i=0; i<strlen(s); i++)
        {
            if(s[i]=='(') sta.push(-1);  //当读入一个“(”时,将-1入栈,表示一个边界
            else if(s[i]==')')           //读入一个“)”时,则把栈中的元素进行出栈操作
            {
                int t1=sta.top(); sta.pop();
                if(t1==-1) continue;
                int t2=sta.top(); sta.pop();
                p[n]=p[t1];
                while(t2!=-1)
                {
                    if(p[t2].y==p[n].x)
                    {
                        sum+=p[t2].x*p[t2].y*p[n].y;
                        p[n].x=p[t2].x;
                    }
                    else
                    {
                        error=1;
                        break;
                    }
                    t2=sta.top(); sta.pop();
                }
                if(error) break;
                sta.push(n++);
            }
            else sta.push(s[i]-'A');
        }
        if(!sta.empty())
        {
            int t1=sta.top(); sta.pop();
            int x=p[t1].x,y=p[t1].y;
            while(!sta.empty())
            {
                t1=sta.top(); sta.pop();
                if(p[t1].y==x)
                {
                    sum+=p[t1].x*x*y;
                    x=p[t1].x;
                }
                else
                {
                    error=1;
                    break;
                }
            }
        }
        if(error) printf("error\n");
        else printf("%d\n",sum);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值