zoukankan      html  css  js  c++  java
  • HDU 1082 Matrix Chain Multiplication

    评估多个矩阵乘法的基本运算次数

    乍一看与分治算法有关,其实题目是个模拟矩阵相乘次数的问题,自定义类型存储矩阵,主要操作用栈实现。遇到'('继续,遇到')'算栈顶两个矩阵相乘并再放进栈顶,附代码

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <stack>
     5 using namespace std;
     6 struct Max {
     7     int row;
     8     int col;
     9 } m[100];
    10 bool flg;
    11 int n,num;
    12 char c,ch[100];
    13 int main() {
    14     //freopen("C:\CODE\in.txt", "r", stdin);
    15     //freopen("C:\CODE\out.txt","w",stdout);
    16     scanf("%d",&n);
    17     for(int i=0; i<n; i++) {
    18         cin>>c>>m[i].row>>m[i].col;
    19     }
    20     getchar();
    21     while(gets(ch)) {
    22         stack<int> s;
    23         flg=false;
    24         int x=30;
    25         num=0;
    26         for(int i=0; i<strlen(ch); i++) {
    27             if(ch[i]=='(')
    28                 continue;
    29             if(ch[i]==')') {
    30                 int a=s.top();
    31                 s.pop();
    32                 int b=s.top();
    33                 s.pop();
    34                 if(m[a].row!=m[b].col) {
    35                     flg=true;
    36                     break;
    37                 } else {
    38                     num+=(m[a].row*m[a].col*m[b].row);
    39                     m[x].row=m[b].row;
    40                     m[x].col=m[a].col;
    41 
    42                     s.push(x);
    43                     x++;
    44                 }
    45             } else {
    46                 s.push(ch[i]-'A');
    47             }
    48         }
    49         if(flg)
    50             puts("error");
    51         else
    52             printf("%d
    ",num);
    53     }
    54 
    55     //fclose(stdin);
    56     return 0;
    57 }
    ---------------- 人们生成的最美好的岁月其实就是最痛苦的时候,只是事后回忆起来的时候才那么幸福。
  • 相关阅读:
    4.数据库表相关操作
    2.快速创建springboot项目 连pom文件里面的配置都不用配了
    1.开始Springboot 基本配置和helloworld
    mysql 对数据库操作的常用sql语句
    mysql简单操作
    1.开始Spring
    关于java中的异常
    关于maven
    npm相关知识点
    git源代码管理工具操作步骤
  • 原文地址:https://www.cnblogs.com/livelihao/p/5177502.html
Copyright © 2011-2022 走看看