EOJ 1051:(算法作业4-1)完全加括号的矩阵连乘积(DP)
2015-09-17 15:52
411 查看
题目链接:http://www.acm.cs.ecnu.edu.cn/problem.php?problemid=1051
题意:给你n的矩阵,要求求出一种加括号的方案使得做的乘法数量最少。
分析:
dp[i][j]表示从i到j的最优解,dp[i][j]=min(dp[i][k]+dp[k][j]+该次乘法次数)dp[i][j] = min(dp[i][k]+dp[k][j] + 该次乘法次数),记忆话搜索即可。
代码:
题意:给你n的矩阵,要求求出一种加括号的方案使得做的乘法数量最少。
分析:
dp[i][j]表示从i到j的最优解,dp[i][j]=min(dp[i][k]+dp[k][j]+该次乘法次数)dp[i][j] = min(dp[i][k]+dp[k][j] + 该次乘法次数),记忆话搜索即可。
代码:
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <stack> #include <set> using namespace std; const int maxn = 50 + 5; const long long INF = (1LL << 63LL) - 1; struct Matrix { int x, y; long long num; friend Matrix operator * (const Matrix& a, const Matrix& b) { Matrix res; res.x = a.x; res.y = b.y; res.num = a.num + b.num + a.x * a.y * b.y; return res; } }; int T, n, ans; Matrix matrix[maxn], dp[maxn][maxn]; Matrix DP(int l, int r) { if (dp[l][r].num >= 0) return dp[l][r]; if (l + 1 == r) { dp[l][r].x = matrix[l].x; dp[l][r].y = matrix[l].y; dp[l][r].num = 0; return dp[l][r]; } dp[l][r].num = INF; for (int i = l + 1; i < r; ++i) { Matrix a = DP(l, i); Matrix b = DP(i, r); Matrix c = a * b; if (c.num < dp[l][r].num) dp[l][r] = c; } return dp[l][r]; } int main() { scanf("%d", &T); for (int C = 0; C < T; ++C) { scanf("%d", &n); for (int i = 0; i <= n; ++i) for (int j = 0; j <= n; ++j) dp[i][j].num = -1; for (int i = 0; i < n; ++i) scanf("%d%d", &matrix[i].x, &matrix[i].y); printf("%lld\n", DP(0, n).num); } return 0; }
相关文章推荐
- centos 安装FTP server详情
- 模板 lucas
- ProxyFactory的一个问题
- MVVM范例:实现 用户列表绑定、编辑 、删除、添加及筛选功能
- 为什么这些脑残应用能活,而那些严肃牛逼的应用死了?
- 活动的启动模式
- 清楚浏览器自动记忆输入的信息
- Spring AOP Example – Advice
- iOS 8 Metal Swift教程 :开始学习
- mocall/free和new/delete的区别
- 清楚浏览器自动记忆输入的信息
- Centos 建立一个新用户 详细讲解
- 制作FAT12软盘以查看软盘的根目录条目+文件属性+文件内容
- 如何通过js和jquery获取图片真实的宽度和高度
- javascript中setInterval的用法
- ZOJ 3898 Stean 矩形法求积分
- 设计模式之: 代理模式
- Metronic_下拉列表Select2插件的使用
- ubuntu系统配置双网卡方法
- Jetty和Tomcat的比较