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;
    }

     

  • 相关阅读:
    PAT A1094 The Largest Generation (25 分)——树的bfs遍历
    PAT A1055 The World's Richest (25 分)——排序
    PAT A1052 Linked List Sorting (25 分)——链表,排序
    PAT A1076 Forwards on Weibo (30 分)——图的bfs
    辅导员
    辅导员面试
    C程序设计
    Excel VBA 基本概念
    Excel函数
    导入excel表的数据到数据库ssh
  • 原文地址:https://www.cnblogs.com/scau20110726/p/2712594.html
Copyright © 2011-2022 走看看