zoukankan      html  css  js  c++  java
  • uva 442 Matrix Chain Multiplication

    //此题其实不是考查矩阵乘法的问题,只是借这个背景来考查栈的运用,注意处理一些细节即可

     

    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    #define MAX 30
    struct matrix
    {int r,c; char e;}a[MAX];
    int n;
    char s[10000010],stack[10000010];
    
    int cmp(struct matrix p ,struct matrix q)
    { return p.e<q.e; }
    
    int main()
    {
        int i,j,k,top,len,sum,c;
    
        scanf("%d",&n); getchar();
        for(i=0; i<n; i++)
        { scanf("%c%d%d",&a[i].e,&a[i].r,&a[i].c); getchar(); }
        sort(a,a+n,cmp);
    
    //    for(i=0; i<n; i++)
    //        printf("%c %d %d\n",a[i].e,a[i].r,a[i].c);
        
    while(scanf("%s",s)!=EOF)
        {
            len=strlen(s);
            if(len==1 && (s[0]>='A' && s[0]<='Z' )) 
            {printf("0\n"); continue;}
    
            for(sum=0,i=0,top=-1; i<len; )
            {
                if(s[i]=='(')  //左括号入栈,s移向下一位
                  stack[++top]=s[i++];
                else if(s[i]>='A' && s[i]<='Z') //字母入栈
                    stack[++top]=s[i++];
                else if(s[i]==')')
                {
                    stack[++top]=s[i];  //先把右括号入栈,放不放其实意义不大
    
                    c=1; 
                    for(j=0; j<n; j++) if(a[j].e==stack[top-2]) break;
                    for(k=0; k<n; k++) if(a[k].e==stack[top-1]) break;
                    if(a[j].c!=a[k].r) break;
    
                    c=a[j].r*a[j].c*a[k].c;  sum+=c;  //计算相乘次数
    
                    a[n].e=a[n-1].e+1; a[n].r=a[j].r; a[n].c=a[k].c; 
                    //每次相乘,就看作是产生了一个新的矩阵,把新的矩阵放入矩阵数组
                    stack[top-3]=a[n].e; top-=3;
                    //保留下新的矩阵在栈中
                    n++; i++;
                }
            }
            if(i<len) printf("error\n");
            else      printf("%d\n",sum);
        }
        return 0;
    }

     

  • 相关阅读:
    github使用技巧
    转载---linux运维相关
    session 测试用例详解
    php中使用linux命令四大步骤
    Thinkphp常用的方法和技巧(转)
    转学步园:jquery offset
    jquery冒泡及阻止
    nginx搭建流媒体服务器的方法详解
    SetTimeOut jquery的作用
    再也不要说,jquery动画呆板了
  • 原文地址:https://www.cnblogs.com/scau20110726/p/2712594.html
Copyright © 2011-2022 走看看