蓝桥 ADV-232 算法提高 矩阵乘法 【区间DP】

  算法提高 矩阵乘法  
时间限制:3.0s   内存限制:256.0MB
    
问题描述
  有n个矩阵,大小分别为a0*a1, a1*a2, a2*a3, ..., a[n-1]*a[n],现要将它们依次相乘,只能使用结合率,求最少需要多少次运算。
  两个大小分别为p*q和q*r的矩阵相乘时的运算次数计为p*q*r。
输入格式
  输入的第一行包含一个整数n,表示矩阵的个数。
  第二行包含n+1个数,表示给定的矩阵。
输出格式
  输出一个整数,表示最少的运算次数。
样例输入
3
1 10 5 20
样例输出
150
数据规模和约定
  1<=n<=1000, 1<=ai<=10000。

题目链接:

  http://lx.lanqiao.cn/problem.page?gpid=T417

题目大意:

  给一个矩阵链乘,只能加括号,问最小矩阵运算次数。

题目思路:

  【区间DP】

  f[i][j]表示i~j的最小代价,枚举拆分点k,f[i][j]=min(f[i][k]+f[k][j]+a[i]*a[k]*a[j])

 1 /****************************************************
 2     
 3     Author : Coolxxx
 4     Copyright 2017 by Coolxxx. All rights reserved.
 5     BLOG : http://blog.csdn.net/u010568270
 6     
 7 ****************************************************/
 8 #include<bits/stdc++.h>
 9 #pragma comment(linker,"/STACK:1024000000,1024000000")
10 #define abs(a) ((a)>0?(a):(-(a)))
11 #define lowbit(a) (a&(-a))
12 #define sqr(a) ((a)*(a))
13 #define mem(a,b) memset(a,b,sizeof(a))
14 const double eps=1e-8;
15 const int J=10000;
16 const int mod=1000000007;
17 const int MAX=0x7f7f7f7f;
18 const double PI=3.14159265358979323;
19 const int N=1004;
20 using namespace std;
21 typedef long long LL;
22 double anss;
23 LL aans;
24 int cas,cass;
25 int n,m,lll,ans;
26 LL a[N];
27 LL f[N][N];
28 int main()
29 {
30     #ifndef ONLINE_JUDGE
31 //    freopen("1.txt","r",stdin);
32 //    freopen("2.txt","w",stdout);
33     #endif
34     int i,j,k,l;
35     int x,y,z;
36 //    for(scanf("%d",&cass);cass;cass--)
37 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
38 //    while(~scanf("%s",s))
39     while(~scanf("%d",&n))
40     {
41         mem(f,0x7f);
42         for(i=1;i<=n+1;i++)
43             scanf("%lld",&a[i]);
44         for(k=1;k<=n;k++)f[k][k+1]=0;
45         for(l=2;l<=n;l++)
46         {
47             for(i=1;i+l<=n+1;i++)
48             {
49                 j=i+l;
50                 for(k=i+1;k<j;k++)
51                 {
52                     f[i][j]=min(f[i][j],f[i][k]+f[k][j]+a[i]*a[k]*a[j]);
53                 }
54             }
55         }
56         printf("%lld
",f[1][n+1]);
57     }
58     return 0;
59 }
60 /*
61 //
62 
63 //
64 */
View Code
原文地址:https://www.cnblogs.com/Coolxxx/p/6671363.html