数字三角形
找一条最大路径。发现从上面往下一步步走很麻烦,直接搜索肯定超时,我们可以逆向求解。从下往上看。从倒数第二行开始看,2可以选4和5,因为找最大,所以我们选5,把2加上5更新为7,以此类推,倒数第二行被更新为7,12,10、10。依次更新到第一行,第一行的数字就是答案。
#include<iostream>using namespace std;const int N = 1010;int r;
int t[N][N];int main()
{cin >> r;for(int i = 0; i < r; i ++ )for(int j = 0; j <= i; j ++ )cin >> t[i][j];for(int i = r - 2; i >= 0; i -- )for(int j = 0; j <= i; j ++ )t[i][j] += max(t[i + 1][j],t[i + 1][j + 1]);cout << t[0][0];return 0;
}
acwing901.滑雪
#include<iostream>
#include<cstring>
#include<algorithm>using namespace std;const int N = 310;int n, m;
int h[N][N];
int f[N][N];
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};int dp(int x, int y)
{if(f[x][y] != -1) return f[x][y];f[x][y] = 1;for(int i = 0; i < 4; i ++ ){int a = x + dx[i], b = y + dy[i];if(a >= 1 && a <= n && b >= 1 && b <= m && h[a][b] < h[x][y])f[x][y] = max(f[x][y], dp(a, b) + 1);}return f[x][y];
}int main()
{cin >> n >> m;for(int i = 1; i <= n; i ++ )for(int j = 1; j <= m; j ++ )cin >> h[i][j];memset(f, -1, sizeof f); int res = 0;for(int i = 1; i <= n; i ++ )for(int j = 1; j <= m; j ++ )res = max(res, dp(i, j));cout << res << endl;return 0;
}