

一开始以为是一道搜索,写了一个简单的dfs之后发现运行超时,又试了一发bfs结果又wa了。。。
后来发现是一道简单的dp。看代码叭。
#include<iostream>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int p = 1e9 + 7;
typedef pair<int, int> pii;
const int N = 510;
ll g[N][N],dis[N][N];
int n;
bool st[N][N];
//int bfs() {
// queue<pii>q;
// q.push({ 1,1 });
// memset(dis, -1, sizeof dis);
// memset(st, false, sizeof st);
// dis[1][1] = g[1][1];
// st[1][1] = true;
// int dx[2] = { 0,1 }, dy[2] = { 1,0 };
// while (q.size())
// {
// auto t = q.front();
// q.pop();
// for (int i = 0; i < 2; i++) {
// int x = t.first + dx[i], y = t.second + dy[i];
// if (x >= 1 && x <= n && y >= 1 && y <= n && dis[x][y] == -1 && !st[x][y]) {
// dis[x][y] = max(dis[x][y],dis[t.first][t.second] + g[x][y]);
// st[x][y] = true;
// q.push({ x, y });
// }
// }
// }
// return dis[n][n];
//}
//int dfs(int i, int j) {
// if (i > n || j > n)return 0;
// else
// if (i == n && j == n) {
// return g[i][j];
// }
// else return max(dfs(i + 1, j), dfs(i, j + 1)) + g[i][j];
//}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> g[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
g[i][j] = max(g[i][j - 1], g[i - 1][j]) + g[i][j];
cout << g[n][n] << endl;
}
中间夹杂了艰辛的,探索历程┭┮﹏┭┮
博主分享了在解决一道动态规划问题时,由尝试深度优先搜索(DFS)和广度优先搜索(BFS)遇到超时和错误,最终发现其实是一道简单的DP问题。详细展示了代码转换和解决方案的过程,值得学习的算法优化案例。
1749

被折叠的 条评论
为什么被折叠?



