• UVa 348 Optimal Array Multiplication Sequence


    这道题是矩阵链,本来想照着书写的,L不在,于是自己想了想,试了试,没想到还真写出来了。。

    看来最难的不是题,而是如何克服畏惧的心(The only thing you have to fear, is fear itself.)。。

    记忆化搜索,打印那里想来想去不知道怎么把几种情况统一起来,也忘了书上怎么处理的。

     1 /* 348 - Optimal Array Multiplication Sequence */
    2 # include <stdio.h>
    3 # include <memory.h>
    4
    5 typedef struct {
    6 int r;
    7 int c;
    8 }mat;
    9
    10 mat m[15];
    11
    12 long long int f[15][15];
    13 int p[15][15];
    14
    15 long long int dp(int s, int e);
    16 void print_list(int s, int e);
    17
    18 int main()
    19 {
    20 int n, i, cnt;
    21
    22 cnt = 0;
    23 while (~scanf("%d", &n))
    24 {
    25 if (0 == n) break;
    26
    27 ++cnt;
    28 memset(f, 0xff, sizeof(f));
    29
    30 for (i = 1; i <= n; ++i)
    31 scanf("%d%d", &m[i].r, &m[i].c);
    32
    33 dp(1, n);
    34
    35 printf("Case %d: ", cnt);
    36 print_list(1, n);
    37 printf("\n");
    38
    39 memset(p, 0, sizeof(p));
    40 }
    41
    42 return 0;
    43 }
    44
    45 long long int dp(int s, int e)
    46 {
    47 int i;
    48 long long t;
    49 if (s == e) return f[s][e] = 0;
    50 if (f[s][e] >= 0) return f[s][e];
    51 f[s][e] = dp(s+1, e) + m[s].r*m[s].c*m[e].c;
    52 p[s][e] = s;
    53 for (i = s+1; i < e; ++i)
    54 {
    55 t = dp(s,i) + dp(i+1, e) + m[s].r*m[i].c*m[e].c;
    56 if (f[s][e] > t) {f[s][e] = t; p[s][e] = i;}
    57 }
    58 return f[s][e];
    59 }
    60
    61 void print_list(int s, int e)
    62 {
    63 if (s > e) return;
    64 if (s == e) {printf("A%d", s); return;}
    65 printf("(");
    66 if (p[s][e] == s)
    67 {
    68 printf("A%d x ", s);
    69 print_list(s+1, e);
    70 }
    71 else if (p[s][e] == e-1)
    72 {
    73 print_list(s, e-1);
    74 printf(" x A%d", e);
    75 }
    76 else
    77 {
    78 print_list(s, p[s][e]);
    79 printf(" x ");
    80 print_list(p[s][e]+1, e);
    81 }
    82 printf(")");
    83 }



  • 相关阅读:
    一条Sql的Spark之旅
    Redis学习笔记:Redis在C#中的使用
    MySQL_表操作
    git上传新项目到coding
    Jenkins 安装 on centos7
    day 36
    表单生成器(Form Builder)之表单数据存储结构mongodb篇
    ORA-16032和ORA-07286 LOG_ARCHIVE_DEST_1没生效
    SQL查询小案例
    mysql从5.6升级到5.7后出现 Expression #1 of ORDER BY clause is not in SELECT list,this is incompatible with DISTINCT
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2430769.html
Copyright © 2020-2023  润新知