hdu 1082, stack emulation, and how to remove redundancy ...

  1. use fgets, and remove the potential ‘\n’ in the string’s last postion.
  2. (main point) remove redundancy
    there must be a stack, at first sight, you need a stack of type myNode, but think deeper, matrix multiplication is valid only if A.c=B.r, then the num of elementary multiplication is A.r*A.c*B.c, note that since A.c=B.r for every contiguous pair of matrices, so we can store the first matrix’s r and c, and for the rest, we first check validation, if error, break, else just store B.c, the B.r is not to been stored, thus remove redundancy.
    //
#include <cstdio>
#include <cstring>
#include <algorithm>

#define MAXSIZE 1000
struct myNode{ int r,c; };

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    int n,i,ch,len,iserror,res, stk[MAXSIZE];
    char buf[MAXSIZE], *p;
    myNode matrices[26], *mat=matrices-'A';
    scanf("%d\n",&n);
    if(n<=0) return -1;
    for(i=0;i<n;++i) {
        ch=getchar();
        scanf("%d%d\n",&mat[ch].r,&mat[ch].c);
    }
    while(fgets(buf,MAXSIZE,stdin)) {
        len=strlen(buf);
        if(buf[len-1]='\n') buf[--len]=0;
        for(res=0,iserror=0, p=buf+1;*p!=0 && *p=='(';++p) {}
        if(*p!=0) {
            stk[0]=mat[*p].r, stk[1]=mat[*p].c;
            for(len=1, ++p;*p!=0;++p) {
                if(*p=='(') continue;
                else if(*p==')') {
                    --len;
                    res+=stk[len-1]*stk[len]*stk[len+1];
                    stk[len]=stk[len+1];
                }
                else {
                    if(mat[*p].r!=stk[len]) { iserror=1; break; }
                    stk[++len]=mat[*p].c;
                }
            }
            while(len>1) {
                --len;
                res+=stk[len-1]*stk[len]*stk[len+1];
                stk[len]=stk[len+1];
            }
        }
        if(iserror) puts("error");
        else printf("%d\n",res);
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。// p.s. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

转载于:https://www.cnblogs.com/qeatzy/p/4716217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值