您的位置:首页 > 汽车 > 时评 > 2766:最大子矩阵

2766:最大子矩阵

2024/9/12 22:22:46 来源:https://blog.csdn.net/Fool256353/article/details/141188972  浏览:    关键词:2766:最大子矩阵

网址如下:

OpenJudge - 2766:最大子矩阵

用dp来做就行了

代码如下(MLE):

#include<cstdio>const int maxn = 101;
int dp[maxn][maxn][maxn][maxn];
int martix[maxn][maxn];
int N, ans;int main(void)
{scanf("%d", &N);//输入for(int i = 1; i <= N; i++)for(int j = 1; j <= N; j++)scanf("%d", &martix[i][j]);//dpans = martix[1][1];for(int x1 = 1; x1 <= N; x1++)for(int y1 = 1; y1 <= N; y1++)for(int x2 = x1; x2 <= N; x2++)for(int y2 = y1; y2 <= N; y2++){dp[x1][y1][x2][y2] = dp[x1][y1][x2 - 1][y2] + dp[x1][y1][x2][y2 - 1] - dp[x1][y1][x2 - 1][y2 - 1] + martix[x2][y2];ans = ans > dp[x1][y1][x2][y2] ? ans : dp[x1][y1][x2][y2];}printf("%d", ans);return 0;
}

虽然内存爆了,但是这个更容易看懂

代码如下(AC):

#include<cstdio>
#include<vector>const int maxn = 101;
std::vector<std::vector<int>> dp[maxn][maxn];
int martix[maxn][maxn];
int N, ans;int main(void)
{scanf("%d", &N);//输入for(int i = 1; i <= N; i++)for(int j = 1; j <= N; j++)scanf("%d", &martix[i][j]);//dpans = martix[1][1];for(int x1 = 1; x1 <= N; x1++)for(int y1 = 1; y1 <= N; y1++){dp[x1][y1].resize(N - x1 + 2);dp[x1][y1][0].resize(N - y1 + 2, 0);for(int x2 = 1; x2 <= N - x1 + 1; x2++){dp[x1][y1][x2].resize(N - y1 + 2, 0);for(int y2 = 1; y2 <= N - y1 + 1; y2++){dp[x1][y1][x2][y2] = dp[x1][y1][x2 - 1][y2] + dp[x1][y1][x2][y2 - 1] - dp[x1][y1][x2 - 1][y2 - 1] + martix[x1 + x2 - 1][y1 + y2 - 1];ans = ans > dp[x1][y1][x2][y2] ? ans : dp[x1][y1][x2][y2];}}dp[x1][y1].clear();}printf("%d", ans);return 0;
}

这个是把内存压下来的代码,dp公式一样,只不过看起来比较复杂

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com