您的位置:首页 > 其它

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] + 该次乘法次数),记忆话搜索即可。

代码:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: