- #include <iostream>
- #include <algorithm>
- using namespace std;
-
- const int N = 510, INF = 1e9;
-
- int n;
- int a[N][N];
- int f[N][N];
-
- int main()
- {
- cin >> n;
- for(int i = 1; i <= n; i ++ )
- for(int j = 1; j <= i; j ++ )
- scanf("%d", &a[i][j]);
-
- for(int i = 0; i <= n; i ++ )
- for(int j = 0; j <= n; j ++ )
- f[i][j] = -INF;
-
- f[1][1] = a[1][1];
- for(int i = 2; i <= n; i ++ )
- for(int j = 1; j <= i; j ++ )
- f[i][j] = max(f[i - 1][j], f[i - 1][j - 1]) + a[i][j];
-
-
- int res = -INF;
- for(int i = 1; i <= n; i ++ ) res = max(res, f[n][i]);
- cout << res << endl;
- return 0;
- }
朴素做法的DP公式:
- #include <iostream>
- #include <algorithm>
- using namespace std;
-
- const int N = 1010;
-
- int n;
- int a[N], f[N];
-
- int main()
- {
- cin >> n;
- for(int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
-
- for(int i = 1; i <= n; i ++ )
- {
- f[i] = 1; // 只有a[i]一个数的情况
- for(int j = 1; j <= i - 1; j ++ )
- if(a[j] < a[i])
- f[i] = max(f[i], f[j] + 1);
- }
-
- int res = 0;
- for(int i = 1; i <= n; i ++ ) res = max(res, f[i]);
-
- cout << res << endl;
-
- return 0;
- }
- #include <iostream>
- #include <algorithm>
- using namespace std;
-
- const int N = 1010;
-
- int n;
- int a[N], f[N];
- int g[N];
-
- int main()
- {
- cin >> n;
- for(int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
-
- for(int i = 1; i <= n; i ++ )
- {
- f[i] = 1; // 只有a[i]一个数的情况
- for(int j = 1; j <= i - 1; j ++ )
- if(a[j] < a[i])
- if(f[i] < f[j] + 1)
- {
- f[i] = f[j] + 1;
- g[i] = j;
- }
- }
-
- int k = 1;
- for(int i = 1; i <= n; i ++ )
- if(f[k] < f[i])
- k = i;
-
- for(int i = 0, len = f[k]; i < len; i ++ )
- {
- cout << a[k] << ' ';
- k = g[k];
- }
-
- return 0;
- }
- #include <iostream>
- #include <algorithm>
-
- using namespace std;
-
- const int N = 1010;
-
- int n, m;
- char a[N], b[N];
- int f[N][N];
-
- int main()
- {
- cin >> n >> m;
- scanf("%s%s",a + 1, b + 1);
-
- for(int i = 1; i <= n; i ++ )
- for(int j = 1; j <= m; j ++ )
- {
- f[i][j] = max(f[i - 1][j], f[i][j - 1]);
- if(a[i] == b[j]) f[i][j] = max(f[i][j], f[i - 1][j - 1] + 1);
- }
- cout << f[n][m] << endl;
- return 0;
- }