【动态规划】洛谷 P1216 [IOI 1994] 数字三角形 Number Triangles
学习资料
1.E01 记忆化搜索 数字三角形
2.E02 线性DP 数字三角形
P1216 [IOI 1994] 数字三角形 Number Triangles
记忆化搜索写法
#include <cstring>
#include <iostream>
using namespace std;
const int N = 1010;
int n;
int a[N][N], f[N][N];
int dfs(int x, int y)
{
if (f[x][y] != -1) return f[x][y];
if (x == n) f[x][y] = a[x][y]; // 最后一层
else f[x][y] = max(dfs(x + 1, y), dfs(x + 1, y + 1)) + a[x][y];
return f[x][y];
}
// 写法二
// int dfs(int x, int y)
// {
// if (f[x][y] != -1) return f[x][y];
// if (x == n) return f[x][y] = a[x][y]; // 最后一层
// f[x][y] = max(dfs(x + 1, y), dfs(x + 1, y + 1)) + a[x][y];
// return f[x][y];
// }
void solve()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++) cin >> a[i][j];
memset(f, -1, sizeof f);
dfs(1, 1);
cout << f[1][1];
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T = 1;
while (T--) solve();
return 0;
}
递推写法一
#include <iostream>
using namespace std;
const int N = 1010;
int n;
int f[N][N];
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++) cin >> f[i][j];
for (int i = n - 1; i >= 1; i--) // 从倒数第2行开始自底向上
for (int j = 1; j <= i; j++)
f[i][j] += max(f[i + 1][j], f[i + 1][j + 1]);
cout << f[1][1] << '\n';
return 0;
}
递推写法二
#include <iostream>
using namespace std;
const int N = 1010;
int n;
int f[N][N];
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++) cin >> f[i][j];
for (int i = n; i >= 2; i--)
for (int j = 1; j <= i - 1; j++)
f[i - 1][j] += max(f[i][j], f[i][j + 1]);
cout << f[1][1] << '\n';
return 0;
}

浙公网安备 33010602011771号